Select Page

# Program to find the most frequent number in the given string using regex

by | Dec 26, 2020 | Python Programs

Home » Python » Python Programs » Program to find the most frequent number in the given string using regex

## Introduction

The task is to find the most occurring number in the given string using regex expression. ## Program

```from collections import Counter
import re

def frequent_no(ip_str):
arr = re.findall(r'[0-9]+', ip_str)
max_freq = 0
ele = 0
count = Counter(arr)
for i in list(count.keys()):
if count[i]>=max_freq:
max_freq = count[i]
ele = int(i)
return ele

ip_str = input("Enter the string: ")
print("The most frequent number in the string {0} is {1}". format(ip_str, frequent_no(ip_str)))
```

## Output ## Explanation

In the above python code our approach is:

• Extract all the numbers from the given string using regex expression.
• Using Counter() function we stored all the numbers with their frequency of occurrence.
• And then we used loop on counter() result to get the most occurred number in the string.

## Author

• A Full Stack Developer with 10+ years of experience in technical content creation.

• 