Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Regular expressions simplify pattern-matching code

Discover the elegance of regular expressions in text-processing scenarios that involve pattern matching

  • Print
  • Feedback

Page 14 of 16

Remove the duplicate whitespace. 


Listing 1 includes System.out.println ("Found " + m.group ());. Notice the call to group(). That method is one of three capturing group-oriented Matcher methods:

  • public int groupCount(): returns the number of capturing groups in a matcher's pattern. That count does not include the special capturing group number 0, which captures the previous match (whether or not a pattern includes capturing groups).
  • public String group(): returns the previous match's characters as recorded by capturing group number 0. That method may return an empty string to indicate a successful match against the empty string. An IllegalStateException object is thrown if either the matcher has not yet attempted a match or the previous match operation failed.
  • public String group(int group): resembles the previous method, except it returns the previous match's characters as recorded by the capturing group number that group specifies. If no capturing group with the specified group number exists in the pattern, the method throws an IndexOutOfBoundsException object.


The following example demonstrates the capturing group methods:

Pattern p = Pattern.compile ("(.(.(.)))");
Matcher m = p.matcher ("abc");
m.find ();
System.out.println (m.groupCount ());
for (int i = 0; i <= m.groupCount (); i++)
     System.out.println (i + ": " + m.group (i));


The example produces the following output:

  • Print
  • Feedback

Resources