Python Regex to Extract Maximum Numeric Value from a String
Given a string containing both text and numbers, the task is to extract the largest numeric value present in it using Python. For example:
Input: "The price is 120 dollars, and the discount is 50, saving 70 more."
Output: 120
Let’s explore different methods to find the maximum numeric value from a string using Python Regex.
Using re.finditer
This method uses "re.finditer()" to iterate through all numeric matches without creating a full list, making it memory-efficient for large strings.
import re
s = "The price is 120 dollars, and the discount is 50, saving 70 more."
m = max(int(match.group()) for match in re.finditer(r'\d+', s))
print(m)
Output
120
Explanation:
- re.finditer(r'\d+', s) returns an iterator for all digit sequences in the string.
- match.group() retrieves each numeric match.
- int() converts it to integer and max() finds the highest numeric value.
Using re.findall and max
This method extracts all numbers at once using "re.findall()" and then finds the largest value with "max()".
import re
s = "The price is 120 dollars, and the discount is 50, saving 70 more."
n = re.findall(r'\d+', s)
m = max(map(int, n))
print(m)
Output
120
Explanation:
- re.findall() extracts all sequences of digits (numeric values) as strings.
- map(int, n) converts the extracted strings into integers.
Using List Comprehension with re.findall()
For those who prefer a more compact approach, we can combine list comprehension and "re.findall()".
import re
s = "The price is 120 dollars, and the discount is 50, saving 70 more."
m = max([int(num) for num in re.findall(r'\d+', s)])
print(m)
Output
120
Explanation:
- re.findall() extracts all numeric parts.
- [int(num) for num in ...] converts them into integers directly.
Custom Parsing with Regex and Loop
This method provides manual control over how numbers are compared and is suitable for custom logic or debugging.
import re
s = "The price is 120 dollars, and the discount is 50, saving 70 more."
m = float('-inf')
for match in re.finditer(r'\d+', s):
num = int(match.group())
m = max(m, num)
print(m)
Output
120
Explanation:
- re.finditer() finds numbers one by one.
- int(match.group()) converts each to integer.
- m = max(m, num) updates the maximum each time.