Matcher: groupCount() : Matcher « java.util.regex « Java by API






Matcher: groupCount()

/*
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
      }
    }
  }

}

           
       








Related examples in the same category

1.Matcher: appendReplacement(StringBuffer sb,String replacement)
2.Matcher.appendTail(StringBuffer sb)
3.Matcher: find()
4.Matcher: group()
5.Matcher: group(int group)
6.Matcher: lookingAt()
7.Matcher: matches()
8.Matcher: replaceAll(String text)
9.Matcher: start()