Open In App
Related Articles

Extract maximum numeric value from a given string | Set 2 (Regex approach)

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 : 365

In Set 1, we have discussed general approach for extract numeric value from given string.In this post, we will discuss regular expression approach for same. Below is one of the regular expression for at least one numeric digit.

\d+

So Regex solution is simple:

  1. Initialize MAX = 0
  2. Run loop over matcher, whenever match found, convert numeric string to integer and compare it with MAX.
    • If number greater than MAX, update MAX to number.
  3. Return MAX at the last.

Implementation:

C++

#include <iostream>
#include <regex>
 
using namespace std;
 
// Method to extract the maximum value
int extractMaximum(string str)
{
    // regular expression for atleast one numeric digit
    string regex = "\\d+";
 
    // compiling regex
    std::regex r(regex);
 
    // sregex_iterator object
    std::sregex_iterator it(str.begin(), str.end(), r);
    std::sregex_iterator end;
 
    // initialize MAX = 0
    int MAX = 0;
 
    // loop over sregex_iterator
    while (it != end) {
        // convert numeric string to integer
        int num = stoi(it->str());
 
        // compare num with MAX, update MAX if num > MAX
        if (num > MAX)
            MAX = num;
 
        it++;
    }
 
    return MAX;
}
 
int main()
{
    string str = "100klh564abc365bg";
 
    cout << extractMaximum(str);
 
    return 0;
}

                    

Java

// Java regex program to extract the maximum value
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
class GFG
{
    // Method to extract the maximum value
    static int extractMaximum(String str)
    {
        // regular expression for atleast one numeric digit
        String regex = "\\d+";
         
        // compiling regex
        Pattern p = Pattern.compile(regex);
         
        // Matcher object
        Matcher m = p.matcher(str);
         
        // initialize MAX = 0
        int MAX = 0;
         
        // loop over matcher
        while(m.find())
        {
            // convert numeric string to integer
            int num = Integer.parseInt(m.group());
             
            // compare num with MAX, update MAX if num > MAX
            if(num > MAX)
                MAX = num;
        }
         
        return MAX;
    }
 
    public static void main (String[] args)
    {
        String str = "100klh564abc365bg";
         
        System.out.println(extractMaximum(str));
    }
}

                    

C#

// C# regex program to extract the maximum value
using System;
using System.Text.RegularExpressions;
 
class GFG
{
  // Method to extract the maximum value
  static int extractMaximum(string str)
  {
 
    // Regex object
    Regex regex = new Regex(@"\d+");
 
 
    // initialize MAX = 0
    int MAX = 0;
 
    // loop over matcher
    foreach (Match ItemMatch in regex.Matches(str))
    {
      // convert numeric string to integer
      int num = Int32.Parse(ItemMatch.Value);
 
      // compare num with MAX, update MAX if num > MAX
      if(num > MAX)
        MAX = num;
    }
 
    return MAX;   
  }
 
  static public void Main ()
  {
    string str = "100klh564abc365bg"
    Console.WriteLine(extractMaximum(str));
  }
}
 
// This code is contributed by kothavvsaakash

                    

Python3

# Python regex program to extract the maximum value
import re
 
# Method to extract the maximum value
def extractMaximum(str):
   
    # regular expression for atleast one numeric digit
    regex = "\\d+"
     
    # compiling regex
    p = re.compile(regex)
     
    # initialize MAX = 0
    MAX = 0
     
    # loop over matcher
    for m in re.finditer(p,str):
       
        # convert numeric string to integer
        num=int(m.group(0))
         
        # compare num with MAX, update MAX if num > MAX
        if(num > MAX):
            MAX = num
             
    return MAX
     
str="100klh564abc365bg"
print(extractMaximum(str))
 
# This code is contributed by Pushpesh Raj.

                    

Javascript

// JavaScript program to extract the maximum value
 
function extractMaximum(str) {
// regular expression for at least one numeric digit
let regex = /\d+/g;
 
// initialize MAX = 0
let MAX = 0;
 
// loop over matches
let match;
while ((match = regex.exec(str)) !== null) {
// convert numeric string to integer
let num = parseInt(match[0]);
 
 
// compare num with MAX, update MAX if num > MAX
if (num > MAX) {
  MAX = num;
}
}
 
return MAX;
}
 
let str = "100klh564abc365bg";
 
console.log(extractMaximum(str));
// this code is contributed by devendra1

                    

Output
564

Time complexity : O(n) 
Auxiliary Space : O(1)

But above program wouldn’t work if number is greater that integer range. You can try parseLong() method for numbers upto long range.But to handle the case of large numbers(greater than long range) we can take help of BigInteger class in java. Below is the java program to demonstrate the same. 

Implementation:

C++

#include <iostream>
#include <regex>
#include <string>
#include <climits>
#include <sstream>
 
using namespace std;
 
// Method to extract the maximum value
long long extractMaximum(string str)
{
    // regular expression for atleast one numeric digit
    regex re("\\d+");
 
    // initializing MAX to be smallest possible value of long long
    long long MAX = LLONG_MIN;
 
    // loop over the string using regex iterator
    for (sregex_iterator i = sregex_iterator(str.begin(), str.end(), re); i != sregex_iterator(); i++) {
        // convert numeric string to long long
        stringstream ss(i->str());
        long long num = 0;
        ss >> num;
 
        // compare num with MAX, update MAX if num > MAX
        if (num > MAX)
            MAX = num;
    }
 
    return MAX;
}
 
int main()
{
    string str = "100klh564231315151313151315abc365bg";
 
    cout << extractMaximum(str) << endl;
 
    return 0;
}

                    

Java

// Java regex program to extract the maximum value
// in case of large numbers
 
import java.math.BigInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
class GFG
{
    // Method to extract the maximum value
    static BigInteger extractMaximum(String str)
    {
        // regular expression for atleast one numeric digit
        String regex = "\\d+";
         
        // compiling regex
        Pattern p = Pattern.compile(regex);
         
        // Matcher object
        Matcher m = p.matcher(str);
         
        // initialize MAX = 0
        BigInteger MAX = BigInteger.ZERO;
         
        // loop over matcher
        while(m.find())
        {
            // convert numeric string to BigInteger
            BigInteger num = new BigInteger(m.group());
             
            // compare num with MAX, update MAX if num > MAX
            if(num.compareTo(MAX) > 0)
                MAX = num;
        }
         
        return MAX;
    }
 
    public static void main (String[] args)
    {
        String str = "100klh564231315151313151315abc365bg";
         
        System.out.println(extractMaximum(str));
    }
}

                    

Python3

import re
 
def extractMaximum(str):
    # Regular expression for at least one numeric digit
    regex = r'\d+'
     
    # Initialize MAX to 0
    MAX = 0
     
    # Loop over matches
    for m in re.finditer(regex, str):
        # Convert numeric string to int
        num = int(m.group())
         
        # Compare num with MAX and update MAX if num > MAX
        if num > MAX:
            MAX = num
             
    return MAX
 
# Example usage
str = "100klh564231315151313151315abc365bg"
print(extractMaximum(str)) # Output: 564231315151313151315

                    

C#

using System;
using System.Text.RegularExpressions;
using System.Numerics;
 
class GFG
{
    static BigInteger ExtractMaximum(string str)
    {
        // Regular expression for at least one numeric digit
        Regex re = new Regex(@"\d+");
 
        // Initializing MAX to be smallest possible value of BigInteger
        BigInteger MAX = BigInteger.MinValue;
 
        // Loop over the string using regex iterator
        foreach (Match m in re.Matches(str))
        {
            // Convert numeric string to BigInteger
            BigInteger num = BigInteger.Parse(m.Value);
 
            // Compare num with MAX, update MAX if num > MAX
            if (num > MAX)
                MAX = num;
        }
 
        return MAX;
    }
 
    static void Main(string[] args)
    {
        string str = "100klh564231315151313151315abc365bg";
        Console.WriteLine(ExtractMaximum(str)); // Output: 564231315151313151315
    }
}
// Big Integer Error : the code is correct but the compilers(online) the reference to
// the 'System.Numerics.dll'
// assembly is not given so in order to show correct output we need
// to add a reference to this assembly in our project

                    

Javascript

// JavaScript regex program to extract the maximum value
// in case of large numbers
 
function extractMaximum(str) {
// regular expression for atleast one numeric digit
const regex = /\d+/g;
 
// Matcher object
let m;
 
// initialize MAX = 0
let MAX = BigInt(0);
 
// loop over matcher
while ((m = regex.exec(str)) !== null) {
// convert numeric string to BigInt
let num = BigInt(m[0]);
 
 
// compare num with MAX, update MAX if num > MAX
if (num > MAX) {
  MAX = num;
}
}
 
return MAX;
}
 
const str = "100klh564231315151313151315abc365bg";
 
console.log(extractMaximum(str));

                    

Output
564231315151313151315

Time complexity : O(n) 
Auxiliary Space : O(1)

 



Last Updated : 17 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads