EN
Java - check if string only contains numbers
0 points
In this article, we would like to show you how to check if the string only contains numbers in Java.
In this example, we use a regular expression (regex) with Pattern.matcher()
to check if the strings contain only numbers.
xxxxxxxxxx
1
import java.util.regex.Matcher;
2
import java.util.regex.Pattern;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
String numbers = "1234";
8
String text = "ABC";
9
10
String regex = "^[0-9]+$"; // regex to check if string contains only digits
11
Pattern pattern = Pattern.compile(regex); // compiles the regex
12
13
// find match between given string and pattern
14
Matcher matcherNumbers = pattern.matcher(numbers);
15
Matcher matcherText = pattern.matcher(text);
16
17
// return true if the string matched the regex
18
Boolean numbersMatches = matcherNumbers.matches();
19
Boolean textMatches = matcherText.matches();
20
21
System.out.println(numbersMatches); // true
22
System.out.println(textMatches); // false
23
}
24
}
Output:
xxxxxxxxxx
1
true
2
false
In this example, we create a function that loops through the string and checks if each character is a digit with Character.isDigit(char ch)
method.
Practical example:
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String numbers = "1234";
5
String text = "ABC";
6
7
System.out.println(onlyNumbers(numbers)); // true
8
System.out.println(onlyNumbers(text)); // false
9
}
10
11
public static boolean onlyNumbers(String string) {
12
if (string == null || string.isEmpty()) {
13
return false;
14
}
15
for (int i = 0; i < string.length(); ++i) {
16
if (!Character.isDigit(string.charAt(i))) {
17
return false;
18
}
19
}
20
return true;
21
}
22
}
Output:
xxxxxxxxxx
1
true
2
false