The matches(String, CharSequence) method of the Pattern class in Java is used to answer whether or not the regular expression matches on the input. To do so we compile the given regular expression and attempts to match the given input against it where both regular expression and input passed as a parameter to the method. If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time.
Syntax:
public static boolean matches(String regex, CharSequence input)
Parameters: This method accepts two parameters:
- regex: This parameter represents the expression to be compiled.
- input: The character sequence to be matched.
Return Value: This method returns a boolean value, answering whether or not the regular expression matches on the input.
Below programs illustrate the matches(String, CharSequence) method:
Program 1:
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
String REGEX = "(.*)(ee)(.*)?" ;
String actualString
= "geeksforgeeks" ;
boolean matcher = Pattern.matches(REGEX, actualString);
if (matcher) {
System.out.println( "match found for Regex." );
}
else {
System.out.println( "No match found for Regex." );
}
}
}
|
Output:
match found for Regex.
Program 2:
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
String REGEX = "(.*)(welcome)(.*)?" ;
String actualString
= "The indian team wins worldcup" ;
boolean matcher = Pattern.matches(REGEX, actualString);
if (matcher) {
System.out.println( "match found for Regex." );
}
else {
System.out.println( "No match found for Regex." );
}
}
}
|
Output:
No match found for Regex.
Reference:
https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#matches(java.lang.String, java.lang.CharSequence)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 May, 2019
Like Article
Save Article