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.
If you are familiar with Java's regular expression API then you must know about java.util.regex.Pattern and java.util.regex.Matcher class, this class provides regular expression capability to Java API.
In this String matches tutorial, we will see two examples of matching the function of the String class :
How to check if a string contains any alphabetic characters or not in both e.g. A-Z or a-Z
How to check if a string contains any numeric digits e.g. digits from 1-9 or 0-9
How to use String.matches() with Regular Expression in Java?
In the following example of matching String using a regular expression, we have used two regular expression metacharacters like dot (.) which matches any character, and as trick or star (*) which matches any number of times.
By using .* we are effectively matching any character coming any number of times in the source String in Java.
Code:
public class StringMatchExample {
public static void main(String args[]) {
String[] alphabets = {"", "12345", "A12345", "12345B",
"12345a" , "abcd" , "aa343"};
for(String alphabet : alphabets) {
System.out.println(" does " + alphabet +
" contains alphabetic words : " + alphabet.matches(".*[A-Za-z].*"));
}
//checking if String contains digits or not
String[] numbers = {"1234" , "+1234", "234a"};
for(String number : numbers) {
System.out.println(" number " + number + " contains only 1-9 digits : "
+ number.matches(".*[1-9].*"));
}
}
}
Output:
The Tech Platform
Comments