Extract Maximum Numeric Value from a String Using Java Regex



In this article, we will learn to extract the maximum numeric value from a string using Java's regex. While Java provides several ways to handle string manipulation, regular expressions (regex) offer a powerful and efficient tool for such tasks.

Problem Statement 

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

Input

String = abcd657efgh234

Output

Maximum numeric value = 657

Using Java Regex and Pattern Class 

Java provides the Pattern and Matcher classes to work with regular expressions. The Pattern class compiles a regular expression, and the Matcher class is used to find matches of the regex pattern in the target string.

Example

Below is an example of extracting the maximum numeric value from a string using Java Regex

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

Using regex with Java Streams

With Java 8 and later, streams provide a more concise and functional programming style for handling tasks like this. The stream API makes it easy to manipulate collections, and when combined with regular expressions, it offers a very clean way to extract and process numeric values.

  • The split() method splits the string by any non-digit characters (\D+). This effectively separates the numbers from the rest of the string.
  • The isEmpty() ensures that we don't process any empty strings that result from consecutive non-digit characters.
  • The mapToInt(Integer::parseInt) converts each numeric string into an integer.
  • The max() method finds the maximum number in the stream, and orElse(0) ensures that if no numbers are found, we default to 0.

Example

import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class MaxNumericExtractorWithStreams {
    public static void main(String[] args) {
        String input = "abc123def456ghi789xyz000";
        System.out.println("Input String: " + input);
        
        // Use streams to extract numbers and find the maximum
        int maxNumber = Arrays.stream(input.split("\D+"))
                            .filter(s -> !s.isEmpty()) 
                            .mapToInt(Integer::parseInt) 
                            .max() 
                            .orElse(0);
        
        // Output the maximum numeric value
        System.out.println("The maximum numeric value in the string is: " + maxNumber);
    }
}

Output

Input String: abc123def456ghi789xyz000
The maximum numeric value in the string is: 789

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2024-12-20T11:33:02+05:30

613 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements