Java Regular Expression to Check If String contains at least One Digit (original) (raw)
This week's task is to write a regular expression in Java to check if a String contains any digit or not. For example, passing "abcd" to pattern should false, while passing "abcd1" to return true, because it contains at least one digit. Similarly passing "1234" should return true because it contains more than one digit. Though java.lang.String class provides a couple of methods with inbuilt support of regular expression like split method, replaceAll(), and matches method, which can be used for this purpose, but they have a drawback. They create a new regular expression pattern object, every time you call. Since most of the time we can just reuse the pattern, we don't need to spend time on creating and compiling patterns, which is expensive compared to testing a String against the pattern.
For reusable patterns, you can take the help of java.util.regex package, it provides two class Pattern and Matcher to create pattern and check String against that pattern.
In order to complete this, we first need to create a regular expression pattern object, we can do that by passing regular expression String "(.)*(\\d)(.)*" to Pattern.compile() method, this returns a compiled version of regular expression String. By using this pattern you can get Matcher object to see if the input string passes this regular expression pattern or not.
We will learn more about our regular expression String in the next section when we will see our code example to check if String contains a number or not.
Regular Expression to Find if String contains Number or Not
The following code sample is our complete Java program to check if String contains any number or not. You can copy this code into your favorite IDE like Eclipse, Netbeans, or IntelliJ IDEA. Just create a Java source file with the name of our public class RegularExpressionDemo and run it from IDE itself.
Alternatively, you can run the Java program from the command line by first compiling a Java source file using the javac compiler and then running it using the java command.
Now let's understand the core of the program, the regular expression itself. We are using "(.)*(\\d)(.)*", where dot and start are meta characters used for any character and any number of timer. \d is a character class for matching digits, and since backward slash needs to escaped in Java, we have put another backslash e.g. \\d..
So if you read this regular expression, it days any character any number of time, followed by any digit then again any character any number of time. This means this will match any String which contains any numeric digit e.g. from 0 - 9.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Java Program to show example of how to use regular expression
* to check if String contains any number or not. Instead of
* using matches() method of java.lang.String, we have used Pattern
* and Matcher class to avoid creating temporary Pattern objects.
*
* @author http://java67.blogspot.com
*/
public class RegularExpressionDemo {
public static void main(String args[]) {
// Regular expression pattern to test input
String regex = "(.)*(\\d)(.)*";
Pattern pattern = Pattern.compile(regex);
Scanner reader = new Scanner(System.in);
String input = "TEST";
System.out.println("Please enter input, must contain at-least one digit");
while (!input.equalsIgnoreCase("EXIT")) {
input = reader.nextLine();
// Pattern pattern = Pattern.compile(regex); // Don't do this, creating Pattern is expensive
Matcher matcher = pattern.matcher(input);
boolean isMatched = matcher.matches();
if (isMatched) {
System.out.println("PASS");
} else {
System.out.println("FAIL, Incorrect input");
}
}
}
}
Output:
Please enter input, must contain at-least one digit
"ABC"
FAIL, Incorrect input
"ABC1"
PASS
""
FAIL, Incorrect input
"1"
PASS
"234"
PASS
"EXIT"
FAIL, Incorrect input
You can see that our pattern behaves correctly and returns true only if the input contains any digit, even for an empty String, it returns false because there is no number on it.
That's all on this post about How to check if a String contains numbers or any numeric digit in Java. You can use this regular expression to separate an alphabetic string from an alphanumeric one. This regular expression and String example also teaches best practices about regex.
If you are checking much String against the same pattern then always use the same pattern object, because the compilation of pattern takes more time than check if a String matches that pattern or not.