The Wayback Machine - https://web.archive.org/web/20240930175122/https://www.geeksforgeeks.org/python-regex-extract-maximum-numeric-value-string/
Open In App

Python Regex to extract maximum numeric value from a string

Last Updated : 31 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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)


Previous Article
Next Article

Similar Reads

Extract maximum numeric value from a given string | Set 2 (Regex approach)
Given an alphanumeric string, extract maximum numeric value from that string. Examples: Input : 100klh564abc365bg Output : 564 Maximum numeric value among 100, 564 and 365 is 564. Input : abchsd0365sdhs Output : 365Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. In Set 1, we have discussed general approach for ex
7 min read
Extract maximum numeric value from a given string | Set 1 (General approach)
Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. One approach to solving the problem is discussed here, other using Regular expressions is given in Set 2 Examples: Input : 100klh564abc365bg Output : 564 Maximum numeric value among 100, 564 and 365 is 564. Input : abchsd0sdhs Output
12 min read
Extract punctuation from the specified column of Dataframe using Regex
Prerequisite: Regular Expression in Python In this article, we will see how to extract punctuation used in the specified column of the Dataframe using Regex. Firstly, we are making regular expression that contains all the punctuation: [!"\$%&\'()*+,\-.\/:;=#@?\[\\\]^_`{|}~]* Then we are passing each row of specific column to re.findall() functi
2 min read
Extract date from a specified column of a given Pandas DataFrame using Regex
In this article, we will discuss how to extract only valid date from a specified column of a given Data Frame. The extracted date from the specified column should be in the form of 'mm-dd-yyyy'. Approach: In this article, we have used a regular expression to extract valid date from the specified column of the data frame. Here we used \b(1[0-2]|0[1-
2 min read
Convert Factor to Numeric and Numeric to Factor in R Programming
Factors are data structures that are implemented to categorize the data or represent categorical data and store it on multiple levels. They can be stored as integers with a corresponding label to every unique integer. Though factors may look similar to character vectors, they are integers, and care must be taken while using them as strings. The fac
5 min read
Limit the Maximum Value of a Numeric Field in a Django Model
Limiting the maximum value of a numeric field in a Django model is essential for maintaining data integrity and preventing errors. By using Django’s built-in validators like MaxValueValidator, implementing custom validation logic in the clean method, and applying constraints in forms, you can ensure that your application handles numeric data effect
3 min read
Find all the patterns of “1(0+)1” in a given string using Python Regex
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0’s. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern. Examples: Input : 1101001 Output : 2 Input : 1000
2 min read
The most occurring number in a string using Regex in python
Given a string str, the task is to extract all the numbers from a string and find out the most occurring element of them using Regex Python. It is guaranteed that no two element have the same frequency Examples: Input :geek55of55geeks4abc3dr2 Output :55Input :abcd1def2high2bnasvd3vjhd44Output :2Approach:Extract all the numbers from a string str usi
2 min read
How to check if a string starts with a substring using regex in Python?
Prerequisite: Regular Expression in Python Given a string str, the task is to check if a string starts with a given substring or not using regular expression in Python. Examples: Input: String: "geeks for geeks makes learning fun" Substring: "geeks" Output: True Input: String: "geeks for geeks makes learning fun" Substring: "makes" Output: FalseChe
3 min read
How to check a valid regex string using Python?
A Regex (Regular Expression) is a sequence of characters used for defining a pattern. This pattern could be used for searching, replacing and other operations. Regex is extensively utilized in applications that require input validation, Password validation, Pattern Recognition, search and replace utilities (found in word processors) etc. This is du
6 min read
Python - Check if String Contain Only Defined Characters using Regex
In this article, we are going to see how to check whether the given string contains only a certain set of characters in Python. These defined characters will be represented using sets. Examples: Input: ‘657’ let us say regular expression contains the following characters- (‘78653’) Output: Valid Explanation: The Input string only consists of charac
2 min read
Remove characters from a numeric string such that string becomes divisible by 8
Given a non-negative integer represented in the form of a numeric string str. Remove zero or more characters from the string such that the number becomes divisible by 8. If it is possible, print the string after removing the characters otherwise print -1.Examples: Input: str = "3454" Output: 344 After removing '5', string becomes 344 which is divis
6 min read
Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation
Given a string S consisting of N digits, the task is to partition the string into at most two increasing subsequences such that concatenation of them also forms an increasing string. If it is not possible to do so, then print "-1". Examples: Input: S = “040425524644”Output: 0022444 44556Explanation:One of the possible way to partition the given str
10 min read
Count subsequences 01 in string generated by concatenation of given numeric string K times
Given a string S and a positive integer K, the task is to find the number of subsequences "01" in the string generated by concatenation of the given numeric string S K times. Examples: Input: S = "0171", K = 2Output: 6Explanation:The string formed by concatenation of S, K number of times is "01710171". There are total 6 possible subsequences which
6 min read
Split a String into columns using regex in pandas DataFrame
Given some mixed data containing multiple values as a string, let's see how can we divide the strings using regex and make multiple columns in Pandas DataFrame. Method #1: In this method we will use re.search(pattern, string, flags=0). Here pattern refers to the pattern that we want to search. It takes in a string with the following values: \w matc
3 min read
Get the first letter of each word in a string using regex in Java
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extract the first letter of each word. It uses '/b'(on
1 min read
Count number of substrings with numeric value greater than X
Given a string 'S' (composed of digits) and an integer 'X", the task is to count all the sub-strings of 'S' that satisfy the following conditions: The sub-string must not begin with the digit '0'.And the numeric number it represents must be greater than 'X'. Note: Two ways of selecting a sub-string are different if they begin or end at different in
5 min read
Maximum XOR value of maximum and second maximum element among all possible subarrays
Given an array arr[] of N distinct positive integers, let's denote max(i, j) and secondMax(i, j) as the maximum and the second maximum element of the subarray arr[i...j]. The task is to find the maximum value of max(i, j) XOR secondMax(i, j) for all possible values of i and j. Note that the size of the subarray must be at least two.Examples: Input:
5 min read
How to convert categorical string data into numeric in Python?
The datasets have both numerical and categorical features. Categorical features refer to string data types and can be easily understood by human beings. However, machines cannot interpret the categorical data directly. Therefore, the categorical data must be converted into numerical data for further processing. There are many ways to convert catego
4 min read
Regex in Python to put spaces between words starting with capital letters
Given an array of characters, which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after the following amendments: Put a single space between these words. Convert the uppercase letters to lowercase Examples: Input : BruceWayneIsBatmanOut
2 min read
Python | Parse a website with regex and urllib
Let's discuss the concept of parsing using python. In python we have lot of modules but for parsing we only need urllib and re i.e regular expression. By using both of these libraries we can fetch the data on web pages. Note that parsing of websites means that fetch the whole source code and that we want to search using a given url link, it will gi
2 min read
Name validation using IGNORECASE in Python Regex
In this article, we will learn about how to use Python Regex to validate name using IGNORECASE. re.IGNORECASE : This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z] will match lowercase letters, too. Generally, It's passed as an optional argument to re.compile(). Let's consider a
2 min read
Verbose in Python Regex
In this article, we will learn about VERBOSE flag of the re package and how to use it. re.VERBOSE : This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class,
3 min read
Python | Swap Name and Date using Group Capturing in Regex
In this article, we will learn how to swap Name and Date for each item in a list using Group Capturing and Numeric Back-referencing feature in Regex . Capturing Group : Parentheses groups the regex between them and captures the text matched by the regex inside them into a numbered group i.e ([\w ]+) which can be reused with a numbered back-referenc
3 min read
Python Regex: re.search() VS re.findall()
Prerequisite: Regular Expression with Examples | Python A Regular expression (sometimes called a Rational expression) is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations. Regular expressions are a generalized way to match patterns with
3 min read
Categorize Password as Strong or Weak using Regex in Python
Given a password, we have to categorize it as a strong or weak one. There are some checks that need to be met to be a strong password. For a weak password, we need to return the reason for it to be weak. Conditions to be fulfilled are: Minimum 9 characters and maximum 20 characters.Cannot be a newline or a spaceThere should not be three or more rep
2 min read
Python Regex - re.MatchObject.start() and re.MatchObject.end() functions
In this article, we are going to see re.MatchObject.start() and re.MatchObject.end() regex methods. re.MatchObject.start() This method returns the first index of the substring matched by group. Syntax: re.MatchObject.start([group]) Parameter: group: (optional) group defaults to zero (meaning the whole matched substring). Return -1 if group exists b
2 min read
re.MatchObject.span() Method in Python - regex
re.MatchObject.span() method returns a tuple containing starting and ending index of the matched string. If group did not contribute to the match it returns(-1,-1). Syntax: re.MatchObject.span() Parameters: group (optional) By default this is 0. Return: A tuple containing starting and ending index of the matched string. If group did not contribute
2 min read
re.MatchObject.group() function in Python Regex
re.MatchObject.group() method returns the complete matched subgroup by default or a tuple of matched subgroups depending on the number of arguments Syntax: re.MatchObject.group([group]) Parameter: group: (optional) group defaults to zero (meaning that it it will return the complete matched string). Return -1 if group exists but did not contribute t
3 min read
re.MatchObject.groupdict() function in Python - Regex
This method returns a dictionary with the groupname as keys and the matched string as the value for that key. Syntax: re.MatchObject.groupdict() Return: A dictionary with groupnames as the keys and matched string as the value for the key. AttributeError: If a matching pattern is not found then it raise AttributeError. Consider the below example: Ex
3 min read