The easiest way to extract the maximum numeric value from a string using regex is to −
For example, for the input string −
There are 121005 people in this city, 1587469 in the neighboring city and 18775994 in a far-off city.
We should get the output −
We can use "\d+" regex to find all numbers in a string as \d signifies a digit and the plus sign finds the longest string of continuous digits. We can implement it using the re package as follows −
import re # Extract all numeric values from the string. occ = re.findall("\d+", "There are 121005 people in this city, 1587469 in the neighbouring city and 18775994 in a far off city.") # Convert the numeric values from string to int. num_list = map(int, occ) # Find and print the max print(max(num_list))
This will give the output −