EN
Java - check if string contains any numbers
0 points
In this article, we would like to show you how to check if a string contains any numbers in Java.
In this example, we use a regular expression (regex) with Pattern.matcher()
to check if the strings contain any 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 text = "ab123cd";
8
9
String regex = ".*\\d.*"; // regex to check if string contains any numbers
10
Pattern pattern = Pattern.compile(regex); // compiles the regex
11
12
// find match between given string and pattern
13
Matcher matcherText = pattern.matcher(text);
14
15
// return true if the string matched the regex
16
Boolean textMatches = matcherText.matches();
17
18
System.out.println(textMatches); // true
19
}
20
}
Output:
xxxxxxxxxx
1
true
In this example, we create a function that loops through the string and checks if any 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 letters = "ABCD";
5
String numbers = "1234";
6
String mixed = "a12b";
7
8
System.out.println(containsNumbers(letters)); // false
9
System.out.println(containsNumbers(numbers)); // true
10
System.out.println(containsNumbers(mixed)); // true
11
}
12
13
public static boolean containsNumbers(String string) {
14
if (string == null || string.isEmpty()) {
15
return false;
16
}
17
for (int i = 0; i < string.length(); ++i) {
18
if (Character.isDigit(string.charAt(i))) {
19
return true;
20
}
21
}
22
return false;
23
}
24
}
Output:
xxxxxxxxxx
1
false
2
true
3
true