Last Updated : 07 Jan, 2025
When working with strings containing both text and numbers, it’s common to extract the largest numeric value embedded within the text, Python’s re
module provides an efficient and concise way to achieve this. In this article, we will explore various methods for this
This is the most simple and efficient approach, it uses the re.findall() method to extract all numeric values and the max() function to find the largest among them.
Python
import re
s = "The price is 120 dollars, and the discount is 50, saving 70 more."
# Extracting all numeric values
n = re.findall(r'\d+', s)
# Finding the maximum value
m = max(map(int, n))
print(m)
Explanation:
Let's explore some more methods and see how Regex is used to extract maximum numeric value from a string.
Using re.finditer for Edge Casesre.finditer() method avoids creating a full list of matches making it memory-efficient for large strings.
Python
import re
s = "The price is 120 dollars, and the discount is 50, saving 70 more."
# Finding maximum numeric value directly
n = max(int(match.group()) for match in re.finditer(r'\d+', s))
print(n)
Explanation:
If we want explicit control over the process, a custom loop can achieve the same result.
Python
import re
s = "The price is 120 dollars, and the discount is 50, saving 70 more."
# Initializing the maximum value
m = float('-inf')
# Using regex to find numeric values
for match in re.finditer(r'\d+', s):
num = int(match.group())
m = max(m, num)
print(m)
Explanation:
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."
#max_value
m = max([int(num) for num in re.findall(r'\d+', s)])
print(m)
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4