EN
Java - check if string contains only digits
12
points
In this article, we would like to show you how in Java, check if a string contains only digits.
Quick solution:
// import java.util.regex.Matcher;
// import java.util.regex.Pattern;
Pattern pattern = Pattern.compile("\\d+"); // or "[0-9]+"
Matcher matcher = pattern.matcher("123456");
System.out.println(matcher.matches()); // true <---- because "123456" contains only numbers
Below we present 2 methods that check if a string contains only numbers:
- Using regular expressions
- Using the
Character.isDigit()
method
1. Using regular expressions
In Java, the Matcher
class and the Pattern
class are most often used to operate on regular expressions. The isOnlyDigits
method returns true if the string contains only numbers otherwise it returns false.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringExample {
private static final Pattern DIGITS_PATTERN = Pattern.compile("\\d+"); // or "[0-9]+"
public static boolean containsOnlyDigits(String text) {
Matcher matcher = DIGITS_PATTERN.matcher(text);
return matcher.matches();
}
public static void main(String[] args) {
System.out.println(containsOnlyDigits("123456")); // true
System.out.println(containsOnlyDigits("1234Sample text..." )); // false
}
}
Output:
true
false
Note:
The
matches
method matches the entire string (not fragments), so there is no need to use^
and$
in the regular expression.
2. Using Character.isDigit()
method
In the solution below, we will convert a string to an array of characters, then go through it and check if each character is a number.
public class StringExample {
public static boolean containsOnlyDigits(String text) {
for (char entry : text.toCharArray()) {
if (!Character.isDigit(entry)) {
return false;
}
}
return true;
}
public static void main(String args[]) {
System.out.println(containsOnlyDigits("123456")); // true
System.out.println(containsOnlyDigits("1234Sample text...")); // false
}
}
Output:
true
false