Check and extract a number from a String in Java

To check if a string contains a number and extract the number from the string in Java, you can use a combination of the matches method of the String class and the find method of the Matcher class.

Here is an example of how you can do this:

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 =;
      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.

I hope this helps! Let me know if you have any other questions.