Can some explain the following output for java regex:(CASE 1)
String s = "topcoder is "
String p = "(top|coder)+";
Pattern pttrn = Pattern.compile(p);
Matcher m = pttrn.matcher(s);
while(m.find()){
System.out.println("group count: " + m.groupCount());
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println("Found : \"" + m.group(i) + "\" as group " + i);
}
System.out.println("Zeroth group:" + m.group(0));
}
produces following output:
group count: 1
Found : "coder" as group 1
Zeroth group:topcoder
Where the following code: (CASE 2)
String s = "topcoder is ";
String p = "(top|coder)";
Pattern pttrn = Pattern.compile(p);
Matcher m = pttrn.matcher(s);
while(m.find()){
System.out.println("group count: " + m.groupCount());
for (int i = 1; i <= m.groupCount(); i++) {
System.out.println("Found : \"" + m.group(i) + "\" as group " + i);
}
System.out.println("Zeroth group:" + m.group(0));
}
produces following output:
group count: 1
Found : "top" as group 1
Zeroth group:top
group count: 1
Found : "coder" as group 1
Zeroth group:coder
Why isn't there are match for top in CASE 1 ? How is + affecting the matching for alternation (|) ?