Python Regex to Extract Maximum Numeric Value from a String (original) (raw)

Last Updated : 29 Oct, 2025

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.

Python `

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)

`

**Explanation:

Using re.findall and max

This method extracts all numbers at once using "re.findall()" and then finds the largest value with "max()".

Python `

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)

`

**Explanation:

Using List Comprehension with re.findall()

For those who prefer a more compact approach, we can combine list comprehension and "re.findall()".

Python `

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)

`

**Explanation:

Custom Parsing with Regex and Loop

This method provides manual control over how numbers are compared and is suitable for custom logic or debugging.

Python `

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)

`

**Explanation: