Matcher: groupCount()

int groupCount()
Returns the number of capturing groups in this matcher's pattern.
 
/*
Group 0: 1
Group 1: 1
Group 2: null
Group 3: null
Group 0: 2
Group 1: 2
Group 2: null
Group 3: null
Group 0: 3
Group 1: 3
Group 2: null
Group 3: null
Group 0: 4.5
Group 1: 4.5
Group 2: .5
Group 3: null
 */
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainClass {

  public static void main(String[] av) {
    String regEx = "[+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)";
    String str = "a b c d e 1 2 3 4.5 ";
    Pattern pattern = Pattern.compile(regEx);
    Matcher m = pattern.matcher(str);
    while(m.find()) {
      for(int i = 0; i<=m.groupCount() ; i++) {
        System.out.println("Group " + i + ": " + m.group(i)); // Group i substring
      }
    }
  }
}
  
Home 
  Java Book 
    Essential Classes  

Matcher:
  1. Regular Expression Processing
  2. Normal character
  3. Wildcard character
  4. Using Wildcards and Quantifiers
  5. Greedy behavior
  6. Working with Classes of Characters
  7. Using replaceAll( )
  8. Using split( )
  9. Matcher: appendReplacement(StringBuffer sb,String replacement)
  10. Matcher.appendTail(StringBuffer sb)
  11. Matcher: find()
  12. Matcher: group()
  13. Matcher: group(int group)
  14. Matcher: groupCount()
  15. Matcher: lookingAt()
  16. Matcher: matches()
  17. Matcher: replaceAll(String text)
  18. Matcher: start()