The Wayback Machine - https://web.archive.org/web/20250118100747/https://www.geeksforgeeks.org/the-most-occurring-number-in-a-string-using-regex-in-python/
Open In App

The most occurring number in a string using Regex in python

Last Updated : 28 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string str, the task is to extract all the numbers from a string and find out the most occurring element of them using Regex Python.

It is guaranteed that no two element have the same frequency

Examples:

Input :geek55of55geeks4abc3dr2 
Output :55

Input :abcd1def2high2bnasvd3vjhd44
Output :2

Approach:Extract all the numbers from a string str using re.findall() function from regex library in python, and with the use of Counter function from collection library we can get the most occurred element.

Below is the Python implementation of above approach

Python3




# your code goes here# Python program to
# find the most occurring element
import re
from collections import Counter
 
def most_occr_element(word):
     
    # re.findall will extract all the elements
    # from the string and make a list
    arr = re.findall(r'[0-9]+', word)   
     
    # to store maxm frequency
    maxm = 0
 
    # to store maxm element of most frequency
    max_elem = 0
     
    # counter will store all the number with
    # their frequencies
    # c = counter((55, 2), (2, 1), (3, 1), (4, 1))   
    c = Counter(arr)
     
    # Store all the keys of counter in a list in
    # which first would we our required element   
    for x in list(c.keys()):
 
        if c[x]>= maxm:
            maxm = c[x]
            max_elem = int(x)
                 
    return max_elem
 
# Driver program
if __name__ == "__main__":
    word = 'geek55of55gee4ksabc3dr2x'
    print(most_occr_element(word))


Output:

55

Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today


Next Article

Similar Reads

three90RightbarBannerImg