Matcher usePattern(Pattern) method in Java with Examples
Last Updated :
25 Mar, 2022
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
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
String regex = "Geeks";
Pattern pattern
= Pattern.compile(regex);
String stringToBeMatched
= "GeeksForGeeks";
Matcher matcher
= pattern
.matcher(stringToBeMatched);
String newPattern = "GFG";
System.out.println("Old Pattern: "
+ matcher.pattern());
matcher = matcher
.usePattern(
Pattern
.compile(newPattern));
System.out.println("New Pattern: "
+ matcher.pattern());
}
}
|
Output:
Old Pattern: Geeks
New Pattern: GFG
Example 2:
Java
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
String regex = "GFG";
Pattern pattern
= Pattern.compile(regex);
String stringToBeMatched
= "GFGFGFGFGFGFGFGFGFG";
Matcher matcher
= pattern
n.matcher(stringToBeMatched);
String newPattern = "Geeks";
System.out.println("Old Pattern: "
+ matcher.pattern());
matcher = matcher
.usePattern(
Pattern
.compile(newPattern));
System.out.println("New Pattern: "
+ matcher.pattern());
}
}
|
Output:
Old Pattern: GFG
New Pattern: Geeks
Reference: Oracle Doc
Share your thoughts in the comments
Please Login to comment...