Role of Matcher.matches() method in Java Regular Expressions


The method java.time.Matcher.matches() matches the given region against the specified pattern. It returns true if the region sequence matches the pattern of the Matcher and false otherwise.

A program that demonstrates the method Matcher.matches() in Java regular expressions is given as follows −

Example

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("Apple");
      String str1 = "apple";
      String str2 = "Apple";
      String str3 = "APPLE";
      Matcher m1 = p.matcher(str1);
      Matcher m2 = p.matcher(str2);
      Matcher m3 = p.matcher(str3);
      System.out.println(str1 + " matches? " + m1.matches());
      System.out.println(str2 + " matches? " + m2.matches());
      System.out.println(str3 + " matches? " + m3.matches());
   }
}

Output

The output of the above program is as follows −

apple matches? false
Apple matches? true
APPLE matches? false

Now let us understand the above program.

Various Matcher patterns are compared with the original pattern “Apple” using the matches() method and the values returned is printed. A code snippet which demonstrates this is as follows −

Pattern p = Pattern.compile("Apple");
String str1 = "apple";
String str2 = "Apple";
String str3 = "APPLE";
Matcher m1 = p.matcher(str1);
Matcher m2 = p.matcher(str2);
Matcher m3 = p.matcher(str3);
System.out.println(str1 + " matches? " + m1.matches());
System.out.println(str2 + " matches? " + m2.matches());
System.out.println(str3 + " matches? " + m3.matches());

Updated on: 30-Jun-2020

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements