pattern() method in Java with examples

In Java, we have the pattern() method of pattern class which helps us find out the regular expression that is compiled to get a pattern. We will see some example programs in this post to explain the working of this method.

pattern() method in Java: Syntax and Examples

The syntax for pattern() method can be given as follows:

public String pattern()

It is evident from the above that this method does not take any parameter. It returns source regular expression that was used to create a pattern.

The below examples will help you understand better how this method works.

Have a look at the given Java program.

import java.io.*;
import java.util.regex.Pattern;

class Example {
  public static void main (String[] args) {
      String regex = "c*t";
      String str = "caat";
      
      Pattern patt = Pattern.compile(regex);
      
      String get_regex = patt.pattern();
      
      System.out.println("Regular expression used : " + get_regex);
  }
}

Output:

Regular expression used : c*t

Here, in the above example, we have used regular expression “c*t” to get a Pattern object patt. When we call pattern() method using this object, it returns the source regular expression as can be seen in the output.

Another Java program to demonstrate the Pattern.pattern() method:

import java.io.*;
import java.util.regex.Pattern;

class Example {
  public static void main (String[] args) {
      String regex = "(code)(.*)?";
      String str = "codespeedy";
      
      Pattern patt = Pattern.compile(regex);
      
      String get_regex = patt.pattern();
      
      System.out.println("Regular expression used : " + get_regex);
  }
}

Output:

Regular expression used : (code)(.*)?

Thank you.

Also read: Password Validation Program in Java

Leave a Reply

Your email address will not be published. Required fields are marked *