Matcher.pattern() method in Java Regular Expressions

Java 8Object Oriented ProgrammingProgramming

The method java.time.Matcher.pattern() returns the pattern that is matched upon by the Matcher. This method accepts no parameters.

A program that demonstrates the method Matcher.pattern() 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[]) {
      String regex = "Apple";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher("AppleIsAFruit");
      System.out.println("Pattern: " + m.pattern());
   }
}

The output of the above program is as follows −

Pattern: Apple

Now let us understand the above program.

The pattern that is matched upon by the Matcher is returned using the Matcher.pattern() method and then printed. A code snippet which demonstrates this is as follows −

String regex = "Apple";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher("AppleIsAFruit");
System.out.println("Pattern: " + m.pattern());
raja
Published on 07-Feb-2019 15:45:35
Advertisements