Dark Mode On/Off

# Python Regex to extract maximum numeric value from a string.

In this tutorial, we will learn to extract maximum numeric value from a string. Here we will have a sequence of characters comprises of numbers and lowercase letters. The number in the string will seperated by lowercase letters.We need to extract a number with maximum value from the given string. We will do so using python regrex.

Python Regex also called REs or regular expressions is a module using which we can specify rules to set the possible strings to match. It is available in `re `module.

Look at the examples to understand the input and output format.

Input: 'ab12cd23f1gh123'

Output: 123

Input: '56g43fr5'

Output: 56

To find a number occurring most of the time, we will use the following approach.

We will use `re.findall()` method to get the list of numbers in the string. To extract the number using '\d+' expression . And find the maximum number from the list.

## Approach: Using findall() and max() method

In this method, we will find the numbers within the input string using `re.findall()` method. Then we will cast the number into integer using `map()` and then use `max()` to find the maximum numeric value from the list.

### Algorithm

Step1: Import re module

Step2: Define a regex expression of number.

Step3: Use the regex method to list out the number in the string.

Step4: Convert the number into integer using `map()` method.

Step5: Find the maximum numeric value using max()

Step6: Print the value.

### Python Program 1

Here is the python program to find maximum numeric value from the string using regex.

``````# import module for regular expression and collections
import re
#input
string='ab12cd123ef23'
#seperate number from string
number = re.findall('\d+', string)
#convert it into integer
number = map(int, number)
print("Max_value:",max(number))``````

### Output

Here is the output of the above program. ### Python Program 2

Let us take one more example for finding max value.

``````# import module for regular expression and collections
import re
#input
string='1bc125cf200c4'
#seperate number from string
number = re.findall('\d+', string)
#convert it into integer
number = map(int, number)
print("Max_value:",max(number))``````

### Output

Here is the output of the above example. ## Conclusion

In this tutorial, we have learned to find maximum numeric value from the given string. We can do this using python regex. It has been explained with examples.