Java Regex to extract maximum numeric value from a string


The maximum numeric value is extracted from an alphanumeric string. An example of this is given as follows −

String = abcd657efgh234
Maximum numeric value = 657

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
 public static void main (String[] args) {
    String str = "123abc874def235ijk999";
    System.out.println("The string is: " + str);
    String regex = "\d+";
    Pattern ptrn = Pattern.compile(regex);
    Matcher match = ptrn.matcher(str);
    int maxNum = 0;
    while(match.find()) {
       int num = Integer.parseInt(match.group());
       if(num > maxNum) {
          maxNum = num;
       }
    }
    System.out.println("The maximum numeric value in above string is: " + maxNum);
 }
}

Output

The string is: 123abc874def235ijk999
The maximum numeric value in above string is: 999

Now let us understand the above program.

First, the string is displayed. Then, regular expression is created for at least one digit. Then regex is compiled and matcher object is created. The code snippet that demonstrates this is given as follows.

String str = "123abc874def235ijk999";
System.out.println("The string is: " + str);
String regex = "\d+";
Pattern ptrn = Pattern.compile(regex);
Matcher match = ptrn.matcher(str);

A while loop is used to find the maximum numeric value in the string. Then maxNum is displayed. The code snippet that demonstrates this is given as follows −

int maxNum = 0;
while(match.find()) {
 int num = Integer.parseInt(match.group());
 if(num > maxNum) {
    maxNum = num;
 }
}
System.out.println("The maximum numeric value in above string is: " + maxNum);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

429 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements