The matches()
method in Java checks if a string matches a regular expression.
The matches()
method can be declared as shown below:
public boolean matches(String exp)
exp
: The regular expression to match the string with.
The matches()
method returns true
if the string matches the regular expression. Otherwise, it returns false
.
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"));}}
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.