Sunday, November 27, 2011

Regular expressions simplify pattern-matching code - 23


The following example demonstrates two of the match position methods reporting start/end match positions for capturing group number 2:
Pattern p = Pattern.compile ("(.(.(.)))");
Matcher m = p.matcher ("abcabcabc");
while (m.find ())
{
   System.out.println ("Found " + m.group (2));
   System.out.println ("  starting at index " + m.start (2) +
                       " and ending at index " + m.end (2));
   System.out.println ();
}

The example produces the following output:
Found bc
  starting at index 1 and ending at index 3
Found bc
  starting at index 4 and ending at index 6
Found bc
  starting at index 7 and ending at index 9

The output shows we are interested in displaying only all matches associated with capturing group number 2, as well as those matches' starting and ending positions.
Note
String incorporates two convenience methods that invoke their equivalent Matcher methods: public String replaceFirst(String regex, String replacement) and public String replaceAll(String regex, String replacement).

No comments: