Java Regular Expression to Check If String contains at least One Digit

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.

10 Regular Expressions Every Java Programmer Should Learn

Regular Expression or regex or regexp is used for String or text matching. You specify a regular expression and then run input String to see if any String matches with your regular expression. There are a lot of use cases of regular expression e.g. you can do find and replace and you can actually search in a big log file for the expression or text you are looking it. Regular expression is not just limited to any programming language like Java but it present everywhere. You use Regular expression in Linux for pattern matching like with grep, find, sed and awk command. Even VI editor allows you to search words using regular expression and popular Windows text editor like Notepad++ and Edit Plus they also support regular expression for search and replace.

How to use String.matches() with Regular Expression in Java? Example Tutorial

String Matching Example in Java
The string matches method in Java can be used to test String against regular expressions in Java. The string matches() method is one of the most convenient ways of checking if a String matches a regular expression in Java or not. Quite often we need to write code that needs to check if String is numeric, Does String contains alphabets e.g. A to Z or a to Z, How to check if String contains a particular digit 6 times, etc. There are so many cases in Java programming where we need a regular expression.