谁能解释一下:
- 为什么下面使用的两种模式给出不同的结果?(下面回答)
- 为什么第二个示例给出的组计数为 1,但说组 1 的开始和结束是 -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 );
}
}
这给出了以下输出:
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