What is the string matches() method in Java?

The matches() method in Java checks if a string matches a regular expression.

Syntax

The matches() method can be declared as shown below:


public boolean matches(String exp)

Parameters

exp: The regular expression to match the string with.

Return value

The matches() method returns true if the string matches the regular expression. Otherwise, it returns false.

Code

Consider the code below, which demonstrates the use of the matches() method.

import java.io.*;
public class Main {
public static void main(String args[]) {
String str = new String("This is matches() example");
System.out.println("str starts with \"This\" :" + str.matches("This(.*)"));
System.out.println("str contains with \"matches()\" :" + str.matches("(.*)matches()(.*)"));
System.out.println("str contains with \"world\" :" + str.matches("(.*)world"));
}
}

Explanation

A string str is declared in line 5. The matches() method is used in lines 7, 9, and 11 to check whether a string matches a regular expression.

Free Resources