The Wayback Machine - https://web.archive.org/web/20250221181318/https://www.geeksforgeeks.org/matcher-pattern-method-in-java-with-examples/
Open In App

Java Matcher pattern() Method

Last Updated : 10 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The pattern() method of the Matcher class is used to get the pattern to be matched by this matcher.

Example 1: The below example demonstrates how the pattern() method retrieves the regex pattern “G.*s$” used to match a string ending with “s” and starting with “G”.

Java
// Java code to illustrate pattern() method
import java.util.regex.*;

public class Geeks 
{
    public static void main(String[] args)
    {
        // Create a pattern from regex
        Pattern pattern = Pattern.compile("G.*s$");

        // Get the String to be matched
        String stringToBeMatched = "GeeksForGeeks";

        // Create a matcher for the input String
        Matcher matcher = pattern.matcher(stringToBeMatched);

        // Get the Pattern using pattern() method
        System.out.println("Pattern used: " + matcher.pattern());
    }
}

Output
Pattern used: G.*s$

Syntax

public Pattern pattern()

  • Parameter: This method do not accepts any parameter.
  • Return Value: This method returns a Pattern which is the pattern to be matched by this Matcher.

Example 2: The below example shows how the pattern() method returns the exact pattern “GFG” used to match repetitive occurrences in a string.

Java
// Java code to illustrate pattern() method
import java.util.regex.*;

public class Geeks 
{
    public static void main(String[] args)
    {
        // Create a pattern from regex
        Pattern pattern = Pattern.compile("GFG");

        // Get the String to be matched
        String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG";

        // Create a matcher for the input String
        Matcher matcher = pattern.matcher(stringToBeMatched);

        // Get the Pattern using pattern() method
        System.out.println("Pattern used: " + matcher.pattern());
    }
}

Output
Pattern used: GFG

Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg