Java Matcher groups: Understanding The difference between "(?:X|Y)" and "(?:X)|(?:Y)"
- by user358795
Can anyone explain:
Why the two patterns used below give different results? (answered below)
Why the 2nd example gives a group count of 1 but says the start
and end of group 1 is -1?
public void testGroups() throws Exception
{
String TEST_STRING = "After Yes is group 1 End";
{
Pattern p;
Matcher m;
String pattern="(?:Yes|No)(.*)End";
p=Pattern.compile(pattern);
m=p.matcher(TEST_STRING);
boolean f=m.find();
int count=m.groupCount();
int start=m.start(1);
int end=m.end(1);
System.out.println("Pattern=" + pattern + "\t Found=" + f + " Group count=" + count +
" Start of group 1=" + start + " End of group 1=" + end );
}
{
Pattern p;
Matcher m;
String pattern="(?:Yes)|(?:No)(.*)End";
p=Pattern.compile(pattern);
m=p.matcher(TEST_STRING);
boolean f=m.find();
int count=m.groupCount();
int start=m.start(1);
int end=m.end(1);
System.out.println("Pattern=" + pattern + "\t Found=" + f + " Group count=" + count +
" Start of group 1=" + start + " End of group 1=" + end );
}
}
Which gives the following output:
Pattern=(?:Yes|No)(.*)End Found=true Group count=1 Start of group 1=9 End of group 1=21
Pattern=(?:Yes)|(?:No)(.*)End Found=true Group count=1 Start of group 1=-1 End of group 1=-1