Java – String matches() method

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)
\sto 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
\dto 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:

References:

Happy Coding !!
Happy Learning !!

Java - String regionMatches() method
Java - String length() method