How do I check if a string contains only digits in Java?

Use String.matches() with the regular expression [0-9]+ to check whether a string contains one or more digits from 0 to 9.

In this example, you will check several strings, including a code with leading zeros, a decimal number, and an empty string.

Source code

Save the following code as DigitsOnlyExample.java:

public class DigitsOnlyExample {
    void main() {
        String[] inputs = {"123", "007", "12a3", "-42", "3.14", " 123 ", ""};

        for (String input : inputs) {
            boolean digitsOnly = input.matches("[0-9]+");
            IO.println("\"" + input + "\": " + digitsOnly);
        }
    }
}

Explanation

The matches() method checks whether the entire string matches the regular expression:

boolean digitsOnly = input.matches("[0-9]+");

The expression has two parts:

Part Meaning
[0-9] Matches one digit from 0 to 9
+ Requires one or more matches

The string "007" matches because leading zeros are allowed. The string "12a3" fails because it contains a letter. Signs, decimal points, and spaces also cause the check to fail.

An empty string fails because + requires at least one digit. Use [0-9]* if an empty string should also pass.

Run the example

Compile and run the file:

javac DigitsOnlyExample.java
java DigitsOnlyExample

Output

"123": true
"007": true
"12a3": false
"-42": false
"3.14": false
" 123 ": false
"": false

The pattern [0-9]+ checks the text without converting it to a number. For example, it accepts "007" as written, and it can match a string whose numeric value is too large for an int.

If your input may contain decimal digits from other scripts, use "\\p{Nd}+" instead. That pattern also accepts digits such as "١٢٣".

Leave a Comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.