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
import re
from collections import Counter
def most_occr_element(word):
arr = re.findall(r '[0-9]+' , word)
maxm = 0
max_elem = 0
c = Counter(arr)
for x in list (c.keys()):
if c[x]> = maxm:
maxm = c[x]
max_elem = int (x)
return max_elem
if __name__ = = "__main__" :
word = 'geek55of55gee4ksabc3dr2x'
print (most_occr_element(word))
|
Output:
55
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
28 Aug, 2023
Like Article
Save Article