Java Reference
In-Depth Information
At the end of this loop the index position is at the character following the last occurrence of the pattern
in the string. If you want to reset the index position to zero, you just call an overloaded version of reset()
for the Matcher object that has no arguments:
m.reset(); //Reset this matcher
This resets the Matcher object to its state before any search operations were carried out. To make sure
you understand the searching process, let's put it all together in an example.
TRY IT OUT: Searching for a Substring
Here's a complete example to search a string for a pattern:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Arrays;
class TryRegex {
public static void main(String args[]) {
// A regex and a string in which to search are specified
String regEx = "had";
String str = "Smith, where Jones had had 'had', had had 'had
had'.";
// The matches in the output will be marked (fixed-width font
required)
char[] marker = new char[str.length()];
Arrays.fill(marker,' ');
// So we can later replace spaces with marker characters
// Obtain the required matcher
Pattern pattern = Pattern.compile(regEx);
Matcher m = pattern.matcher(str);
// Find every match and mark it
while( m.find() ){
System.out.println(
"Pattern found at Start: " + m.start() + " End: " +
m.end());
Arrays.fill(marker,m.start(),m.end(),'^');
}
// Show the object string with matches marked under it
System.out.println(str);
System.out.println(marker);
}
}
Search WWH ::




Custom Search