Checking if a String Contains Numbers in Java
In Java, determining whether a string contains numbers is a common task. Whether you’re validating user input or processing data, it’s crucial to efficiently check for numeric presence. In this blog, we’ll explore various methods to achieve this, providing practical code examples.
Method 1: Using Regular Expressions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringContainsNumbers {
public static boolean containsNumbers(String input) {
Pattern pattern = Pattern.compile(".*\\d.*");
Matcher matcher = pattern.matcher(input);
return matcher.matches();
}
public static void main(String[] args) {
String testString = "Hello123";
if (containsNumbers(testString)) {
System.out.println("String contains numbers.");
} else {
System.out.println("String does not contain numbers.");
}
}
}
|
Method 2: Iterating Through Characters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class StringContainsNumbers {
public static boolean containsNumbersIterative(String input) {
for (char character : input.toCharArray()) {
if (Character.isDigit(character)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
String testString = "Hello123";
if (containsNumbersIterative(testString)) {
System.out.println("String contains numbers.");
} else {
System.out.println("String does not contain numbers.");
}
}
}
|
Method 3: Apache Commons Lang
If you’re using Apache Commons Lang library, you can simplify the process.
1
2
3
4
5
6
7
8
9
10
11
12
|
import org.apache.commons.lang3.StringUtils;
public class StringContainsNumbers {
public static void main(String[] args) {
String testString = "Hello123";
if (StringUtils.containsAny(testString, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9')) {
System.out.println("String contains numbers.");
} else {
System.out.println("String does not contain numbers.");
}
}
}
|
In this blog, we covered three methods to check if a string contains numbers in Java. Each approach has its advantages, so choose the one that best fits your requirements.
Sharing is caring!