Numbers only regex (digits only) Java

Numbers only (digits only)

Numbers only (or digits only) regular expressions can be used to validate if a string contains only numbers.

Basic numbers only regex

Below is a simple regular expression that allows validating if a given string contains only numbers:

Pattern.compile("^\\d+$")

Test it!
/^\d+$/

True

False

Enter a text in the input above to see the result

Example code in Java:

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.Arrays;

public class Main {

    public static void main(String []args) {
        // Validate number
        boolean isMatch = Pattern.compile("^\\d+$")
               .matcher("42")
               .find(); 
        System.out.println(isMatch); // prints true
        
        // Extract number from a string
        String[] matches = Pattern.compile("\\d+")
                          .matcher("Your message was viewed 203 times.")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
        System.out.println(Arrays.toString(matches)); // prints [203]
    }
}

Real number regex

Real number regex can be used to validate or exact real numbers from a string.

Pattern.compile("^(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)$")

Test it!
/^(?:-(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))|(?:0|(?:[1-9](?:\d{0,2}(?:,\d{3})+|\d*))))(?:.\d+|)$/

True

False

Enter a text in the input above to see the result

Example code in Java:

import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.Arrays;

public class Main {

    public static void main(String []args) {
        // Validate real number
        boolean isMatch = Pattern.compile("^(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)$")
               .matcher("121220.22")
               .find(); 
        System.out.println(isMatch); // prints true
        
        // Extract real number from a string
        String[] matches = Pattern.compile("(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)")
                          .matcher("Pi equals to 3.14")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
        System.out.println(Arrays.toString(matches)); // prints [3.14]
    }
}

Test it!

True

False

Enter a text in the input above to see the result

Notes on number only regex validation

In Java you can also validate number by trying to parse it:

try {
    double d = Double.parseDouble("1.12");
} catch (NumberFormatException nfe) {
    return false;
}