How to Reset the Pattern of a Regular Expression?
Last Updated :
13 Feb, 2024
A regular expression pattern in Java is defined using the Pattern class, which is a component of the java.util.regex package. But sometimes, we may wish to reset the internal state of the Pattern object or use it again with a different input string. This helps to improve efficiency in instances where pattern matching occurs often by avoiding the need to recreate the Pattern object numerous times.
Resetting the Pattern of a Regular Expression in Java
We may reset the internal state of the Pattern object in Java using the reset() method of the Pattern class. When we want to match against several input strings using the same Pattern object again, this is helpful.
Let’s look at a simple example to understand how to reset a regular expression’s pattern in Java:
Java
import java.util.regex.*;
public class PatternResetExample {
public static void main(String[] args)
{
Pattern pattern = Pattern.compile( "\\d+" );
Matcher matcher = pattern.matcher( "8520" );
if (matcher.find()) {
System.out.println( "Match found: " + matcher.group());
}
matcher.reset( "kkhgt5678" );
System.out.println( "After resetting the Matcher " );
if (matcher.find()) {
System.out.println( "Match found: " + matcher.group());
}
}
}
|
Output
Match found: 8520
After resetting the Matcher
Match found: 5678
Explaination of the above Program:
- Create a Pattern Object
- Use the Matcher to Match against a String
- Reset the Pattern for a Different String
This demonstrates the successful reset of the Pattern for a different input string.
Share your thoughts in the comments
Please Login to comment...