Skip to content

How to check if a string contains only digits in Java

To check if a string contains only digits in Java, you can use the matches() method of the String class in combination with the regular expression "\\d+". The matches() method returns true if the string matches the regular expression, and false if it does not. Note that in Java, matches() implicitly anchors the pattern to the start and end of the string, so it validates the entire content.

Here is an example of how you can use the matches() method to check if a string contains only digits:


java
String str = "12345";
boolean isDigits = str.matches("\\d+");  // isDigits is true

The regular expression "\\d+" matches one or more digits (\\d), so the string must contain at least one digit to be considered a match. This approach already returns false for empty strings.

Alternatively, you can use the CharSequence.chars() method and the Character.isDigit() method to check if each character in the string is a digit:


java
String str = "12345";
boolean isDigits = str.chars().allMatch(Character::isDigit);  // isDigits is true

Keep in mind that the stream-based approach treats an empty string as containing only digits (since allMatch returns true for empty streams). If you want to treat an empty string as not containing only digits, you can add an additional check for an empty string:

For example:


java
String str = "12345";
boolean isDigits = !str.isEmpty() && str.chars().allMatch(Character::isDigit);  // isDigits is true

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.