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 contain more than one digit. Though
java.lang.String class provides couple of methods with inbuilt support of regular expression e.g.
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 pattern, which is expensive compare to testing an
String against pattern. For reusable patterns, you can take 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 input string passes this regular expression pattern or not. We will learn more about our
regular expression String in next section, when we will see our code example for check if String contains a number or not.