Open In App

Java Matcher pattern() Method

Last Updated : 11 Jul, 2025
Suggest changes
Share
7 Likes
Like
Report

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 does not accept any parameter(s).
  • 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 

Explore