Skip to content

Check and extract a number from a String in Java

To check if a string contains a number and extract it in Java, you can use the Pattern and Matcher classes from the java.util.regex package.

Here is an example of how you can do this:


java
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) throws Exception {
    String s = "Hello, world! The number is 42.";

    // Check if the string contains a number
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(s);
    if (m.find()) {
      // Extract the number from the string
      String number = m.group();
      System.out.println("Number: " + number);  // Outputs "Number: 42"
    } else {
      System.out.println("No number found.");
    }
  }
}

This code uses a regular expression to search for one or more consecutive digits in the string. It then uses the find method of the Matcher object to check if a match was found. If a match was found, the group method is used to extract the matched string, which is the number. Note that this approach only extracts the first number found in the string, and it does not handle negative numbers or decimals.

Dual-run preview — compare with live Symfony routes.