Pattern pattern() method in Java with Examples

The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression.

Syntax:

public String pattern()

Parameters: This method does not accepts anything as parameter.

Return Value: This method returns the pattern’s source regular expression.

Below programs illustrate the pattern() method:
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// Pattern.pattern() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a REGEX String
        String REGEX = "(.*)(for)(.*)?";
  
        // create the string
        // in which you want to search
        String actualString
            = "code of Machine";
  
        // create pattern
        Pattern pattern1 = Pattern.compile(REGEX);
  
        // find the regular expressio of pattern
        String RegularExpression = pattern1.pattern();
  
        System.out.println("Pattern's RegularExpression = "
                           + RegularExpression);
    }
}

chevron_right


Output:

Pattern's RegularExpression = (.*)(for)(.*)?

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// Pattern.compile method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a REGEX String
        String REGEX = "(.*)(ee)(.*)?";
  
        // create the string
        // in which you want to search
        String actualString
            = "geeks";
  
        // create pattern
        Pattern pattern1 = Pattern.compile(REGEX);
  
        // find the regular expressio of pattern
        String RegularExpression = pattern1.pattern();
  
        System.out.println("Pattern's RegularExpression = "
                           + RegularExpression);
    }
}

chevron_right


Output:

Pattern's RegularExpression = (.*)(ee)(.*)?

References:
https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#pattern()



My Personal Notes arrow_drop_up

I am a Developer I love to code and bring my ideas alive

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.