The usePattern() method of Matcher Class is used to get the pattern to be matched by this matcher. Syntax:
public Matcher usePattern(Pattern newPattern)
Parameters: This method takes a parameter newPattern which is the new pattern to be set. Return Value: This method returns a Matcher with the new Pattern. Exception: This method throws IllegalArgumentException if newPattern is null. Below examples illustrate the Matcher.usePattern() method: Example 1:Â
Java
// Java code to illustrate usePattern() methodÂ
import java.util.regex.*;Â
public class GFG {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â
        // Get the regex to be checked        String regex = "Geeks";Â
        // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);Â
        // Get the String to be matched        String stringToBeMatched            = "GeeksForGeeks";Â
        // Create a matcher for the input String        Matcher matcher            = pattern                  .matcher(stringToBeMatched);Â
        // Get the new Pattern        String newPattern = "GFG";Â
        // Get the Pattern using pattern method        System.out.println("Old Pattern: "                           + matcher.pattern());Â
        // Set the newPattern using usePattern() method        matcher = matcher                      .usePattern(                          Pattern                              .compile(newPattern));Â
        // Get the Pattern        // using pattern method        System.out.println("New Pattern: "                           + matcher.pattern());    }} |
Old Pattern: Geeks New Pattern: GFG
Example 2:Â
Java
// Java code to illustrate usePattern() methodÂ
import java.util.regex.*;Â
public class GFG {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â
        // Get the regex to be checked        String regex = "GFG";Â
        // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);Â
        // Get the String to be matched        String stringToBeMatched            = "GFGFGFGFGFGFGFGFGFG";Â
        // Create a matcher for the input String        Matcher matcher            = pattern                  n.matcher(stringToBeMatched);Â
        // Get the new Pattern        String newPattern = "Geeks";Â
        // Get the Pattern using pattern method        System.out.println("Old Pattern: "                           + matcher.pattern());Â
        // Set the newPattern using usePattern() method        matcher = matcher                      .usePattern(                          Pattern                              .compile(newPattern));Â
        // Get the Pattern        // using pattern method        System.out.println("New Pattern: "                           + matcher.pattern());    }} |
Old Pattern: GFG New Pattern: Geeks
Reference: Oracle Doc
