Open In App
Related Articles

Python Regex to extract maximum numeric value from a string

Improve Article
Improve
Save Article
Save
Like Article
Like

Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case.

Examples:

Input : 100klh564abc365bg
Output : 564
Maximum numeric value among 100, 564
and 365 is 564.

Input : abchsd0sdhs
Output : 0

Python Regex to extract maximum numeric value from a string

This problem has existing solution please refer Extract maximum numeric value from a given string | Set 1 (General approach) link. We will solve this problem quickly in python using Regex. Approach is very simple,

  1. Find list of all integer numbers in string separated by lower case characters using re.findall(expression,string) method.
  2. Convert each number in form of string into decimal number and then find max of it.

Implementation:

Python




# Function to extract maximum numeric value from
# a given string
import re
 
def extractMax(input):
 
     # get a list of all numbers separated by
     # lower case characters
     # \d+ is a regular expression which means
     # one or more digit
     # output will be like ['100','564','365']
     numbers = re.findall('\d+',input)
 
     # now we need to convert each number into integer
     # int(string) converts string into integer
     # we will map int() function onto all elements
     # of numbers list
     numbers = map(int,numbers)
 
     print max(numbers)
 
# Driver program
if __name__ == "__main__":
    input = '100klh564abc365bg'
    extractMax(input)


Output

564

Time complexity : O(n), where n is the length of the input string. This is because the function iterates through the input string once to find all the numbers using the regular expression, and then iterates through the numbers again to convert them to integers.

Space complexity :  O(n)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 31 Jul, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials