Java Reference
In-Depth Information
m.reset(); //Reset this matcher
This resets the Matcher object to its original state before any search operations were carried out.
To make sure we 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(new String(marker));
}
}
This will produce the output:
Pattern found at Start: 19 End: 22
Pattern found at Start: 23 End: 26
Pattern found at Start: 28 End: 31
Pattern found at Start: 34 End: 37
Pattern found at Start: 38 End: 41
Pattern found at Start: 43 End: 46
Pattern found at Start: 47 End: 50
Smith, where Jones had had 'had', had had 'had had'.
^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^
Search WWH ::




Custom Search