# Reset the Matcher in Java Regular Expressions

The Matcher can be reset using the java.util.regex.Matcher.reset() method. This method returns the reset Matcher.

A program that demonstrates the method Matcher.reset() in Java regular expressions is given as follows:

## Example

Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainClass {
public static void main(String args[]) {
Pattern p = Pattern.compile("(a*b)");
Matcher m = p.matcher("caaabcccab");
System.out.println("The input string is: caaabcccab");
System.out.println("The Regex is: (a*b)");
System.out.println();
while (m.find()) {
System.out.println(m.group());
}
m.reset();
System.out.println("The Matcher is reset");
while (m.find()) {
System.out.println(m.group());
}
}
}

## Output

The input string is: caaabcccab
The Regex is: (a*b)
aaab
ab
The Matcher is reset
aaab
ab

Now let us understand the above program.

The subsequence “(a*b)” is searched in the string sequence "caaabcccab". Then the find() method is used to find if the subsequence is in the input sequence and the required result is printed. The Matcher.reset() method is used to reset the Matcher. Then he find() method is used again and the required result is printed.

A code snippet which demonstrates this is as follows:

Pattern p = Pattern.compile("(a*b)");
Matcher m = p.matcher("caaabcccab");
System.out.println("The input string is: caaabcccab");
System.out.println("The Regex is: (a*b)");
System.out.println();
while (m.find()) {
System.out.println(m.group());
}
m.reset();
System.out.println("The Matcher is reset");
while (m.find()) {
System.out.println(m.group());
}
Rishi Raj

I am a coder