In this article, we will discuss matches() method of String class which is used to compare invoking string with the specified regex
1. String’s matches() method:
- This String method is used to check whether invoking-string matches specified-regex (regular expression)
1.1 Method Signature:
public boolean matches(String regex);
1.2 Returns:
- returns true, if the invoking-string matches the specified regular expression
- returns false, if the invoking-string doesn’t matches specified-regex
1.3 Throws:
- PatternSyntaxException, if the specified regex syntax is invalid (or simply not compliable)
2. Examples on matches() method:
- In the below example, we will use different strings to match with the specified regex
- And print corresponding results to console
StringMatchesMethod.java
package in.bench.resources.string.methods;
public class StringMatchesMethod {
public static void main(String[] args) {
// Test String 1 :
// checking particular word with regex pattern
String str1 = "This is Java world";
System.out.println("Whether 'Java' present ? : "
+ str1.matches("(.*)Java(.*)"));
System.out.println("Whether 'Hello' present ? : "
+ str1.matches("(.*)Hello(.*)"));
// Test String 2 :
// checking alphabetic pattern with regex
String str2 = "This is 1 Java world";
System.out.println("\nOnly alphabets ? : "
+ str2.matches("[a-zA-Z]*"));
System.out.println("Whether alpha-numeric ? : "
+ str2.matches("^[a-zA-Z0-9\\s]*$"));
// Test String 3 :
// checking ending with 2 digits
String str3 = "this string has length of 10";
System.out.println("\nOnly numerics ? : "
+ str3.matches("[0-9]*"));
System.out.println("Whether ending with 2-digits : "
+ str3.matches(".*[0-9]{2}"));
// Test String 4 :
// checking numeric(1-9) followed by 2-alphabets ending
String str4 = "123456789 Yo";
System.out.println("\nWhether ending with "
+ "2-alphabets ? :"
+ str4.matches("[1-9\\s]*[A-Za-z]{2}"));
System.out.println("Whether ending with space and "
+ "2-alphabets ? : "
+ str4.matches("[1-9]*[\\s]{1}[A-Za-z]{2}"));
}
}
Output:
Whether 'Java' present ? : true
Whether 'Hello' present ? : false
Only alphabets ? : false
Whether alpha-numeric ? : true
Only numerics ? : false
Whether ending with 2-digits : true
Whether ending with 2-alphabets ? : true
Whether ending with space & 2-alphabets ? : true
3. Regular expression or regex patterns:
. | to specifies any characters (DOT or period) |
* | to specify any number of times (0 or more) (asterisk) |
\s | to specify one space character |
[a-zA-Z] | to specify a through z and A through Z (all inclusive) |
[a-z] | a through z, only |
[A-Z] | A through Z, only |
\d | to specify any digits between [0-9] |
[0-9] | to specify any digits between [0-9] |
[1-9] | to specify digits between [1-9] |
Q) How to build regex pattern ?
- Step 1: First thing, what pattern is required like whether,
- Only alphabets
- Only numbers
- Only alpha-numeric
- Starting with some alphabets or numbers
- Ending with some alphabets or numbers
- Step 2: Once after deciding pattern, take help of above table to build your pattern,
- Like for only alphabets, use either [A-Z] for uppercase letter and [a-z] for lowercase letters
- otherwise, we can use combination of both like [a-zA-Z] or [A-Za-z] for covering all alphabets
- for numerals either [0-9] or [\d]
- for any character matching specify “.” (DOT or period)
- Later, you need to specify the number of times, it is allowed to repeat
- Step 3: How many times specified character or numerals or special character is allowed to repeat
- Like for any number of times, specify ‘*’ (asterisk)
- Or else, if we want specify number of times then specify within curly braces {} as shown in the above example case.4
- Step 4: Take extra-care for special characters like space, under-score, backward-slash, etc
- Always escape sequence for special characters
- Otherwise it will throw compile-time error
Hope, you found this article very helpful. If you any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.
Related Articles:
- Java – String charAt(int index) method
- Java – String compareTo(String anotherString) method
- Java – String compareToIgnoreCase(String str) method
- Java – String concat(String str) method
- Java – String contains(CharSequence s) method
- Java – String contentEquals(StringBuffer sb) method
- Java – String copyValueOf(char[] data) method (2)
- Java – String endsWith(String suffix) method
- Java – String equals(Object anObject) method
- Java – String equalsIgnoreCase(Object anObject) method
- Java – String format(String format, Object… args) method
- Java – String getBytes() method (4)
- Java – String getChars() method
- Java – String hashCode() method
- Java – String indexOf() method (4)
- Java – String intern() method
- Java – String isEmpty() method
- Java – String join() method (2)
- Java – String lastIndexOf() method (4)
- Java – String length() method
- Java – String matches(String regex) method
- Java – String regionMatches() method (2)
- Java – String replace(char oldChar, char newChar) method
- Java – String replace(CharSequence target, CharSequence replacement) method
- Java – String replaceAll(String regex, String replacement) method
- Java – String replaceFirst(String regex, String replacement) method
- Java – String split(String regex) method
- Java – String split(String regex, int limit) method
- Java – String startsWith(String prefix) method
- Java – String startsWith(String prefix, int toffset) method
- Java – String subSequence(int beginIndex, int endIndex) method
- Java – String substring(int beginIndex) method
- Java – String substring(int beginIndex, int endIndex) method
- Java – String toCharArray() method
- Java – String toLowerCase() method (2)
- Java – String toUpperCase() method (2)
- Java – String toString() method
- Java – String trim() method
- Java – String valueOf() method (9)
References:
- https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
- https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
- https://docs.oracle.com/javase/tutorial/java/data/strings.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html
- https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sum
Happy Coding !!
Happy Learning !!