The most occurring number in a string using Regex in python
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
# 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)) |
55
Recommended Posts:
- Find all the patterns of “1(0+)1” in a given string using Python Regex
- Python | Check if string matches regex list
- Python Regex to extract maximum numeric value from a string
- Python Regex - Program to accept string starting with vowel
- Python Regex | Program to accept string ending with alphanumeric character
- Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
- Python regex | Check whether the input is Floating point number or not
- Split a String into columns using regex in pandas DataFrame
- Verbose in Python Regex
- Pattern matching in Python with Regex
- Name validation using IGNORECASE in Python Regex
- Python | Program that matches a word containing 'g' followed by one or more e's using regex
- Python | Parse a website with regex and urllib
- Python | Swap Name and Date using Group Capturing in Regex
- Regex in Python to put spaces between words starting with capital letters
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



