String matches() Method

This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str).

Syntax of String matches() method

public boolean matches (String regex)

Parameters

  • regex: The regular expression to which this string is to be matched. 

Return Type

  • Boolean value, returning true if and only if strings match the given regular expression else false.

Example of String matches() Method

Java




// Java Program to Demonstrate Working of matches() Method
// of String class
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Declaring and initializing a string
        // Input string
        String Str = new String("Welcome to w3wiki");
 
        // Display message for better readability
        System.out.print(
            "Does String contains regex (.*)geeks(.*) ? : ");
        // Testing if regex is present or not
        System.out.println(Str.matches("(.*)geeks(.*)"));
 
        // Display message for better readability
        System.out.print(
            "Does String contains regex geeks ? : ");
 
        // Testing if regex is present or not
        System.out.println(Str.matches("geeks"));
    }
}


Output

Does String contains regex (.*)geeks(.*) ? : true
Does String contains regex geeks ? : false

String matches() Method in Java with Examples

Variants of matches() method is used to tell more precisely not test whether the given string matches to a regular expression or not as whenever this method is called in itself as matches() or be it matches() where here we do pass two arguments that are our string and regular expression, the working and output remains same.

Similar Reads

Variants of String matches() Method

There exist multiple variants three variants of the matches() method, as listed and described below, as follows:...

1. String matches() Method

This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str)....

2. String regionMatches() Method

...

3. String regionMatches() with ignoreCase

...

Contact Us