The most occurring number in a string using Regex in python



In this tutorial, we are going to write a regex that finds the most occurring number in the string. We will check the regex in Python.

Follow the below steps to write the program.

  • Import the re and collections modules.
  • Initialize the string with numbers.
  • 4Find all the numbers using regex and store them in the array.
  • Find the most occurring number using Counter from collections module.

Example

 Live Demo

# importing the modules import re import collections # initializing the string string = '1222tutorials321232point3442' # regex to find all the numbers regex = r'[0-9]' # getting all the numbers from the string numbers = re.findall(regex, string) # counter object counter = collections.Counter(numbers) # finding the most occurring number high_frequency = 0 highest_frequency_number = None for key in list(counter.keys()):    if counter[key] > high_frequency:       highest_frequency_number = counter[key]       # printing the number print(highest_frequency_number)

Output

If you run the above code, then you will get the following result.

2

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 2020-07-11T08:18:27+05:30

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements