Python Regex to extract maximum numeric value from a string

PythonProgrammingServer Side Programming

The easiest way to extract the maximum numeric value from a string using regex is to −

  • Use the regex module to extract all the numbers from a string
  • Find the max from these numbers

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 −

18775994

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 −

18775994
raja
Published on 02-Aug-2018 13:32:21
Advertisements