我有代码为
String regexpr = "(abc)(ab)(cd)";
String test = "abcabcd";
Pattern p = Pattern.compile(regexpr);
Matcher m = p.matcher(test);
while(m.find ())
{
System.out.println(m.group());
}
此代码给出的输出为
abcabcd
But I want to print all the groups in the matched string i.e
group 1 abc
group 2 ab
group 3 cd
我试过了
int i=1;
while (m.group(i) != null)
{
System.out.println("group" + i + m.group(i));
i++;
}
我得到了
group 1 abc
group 2 ab
group 3 cd
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 4
如何避免这种异常?
以及如何打印所有组的开始和结束索引?
最佳答案
您可以打印所有组的开始和结束索引
while (i<=m.groupCount())
{
System.out.println("group" + i + m.group(i));
System.out.println("starting index:" + m.start(i) + "Ending Index:" + m.end(i));
i++;
}
关于java - 当我尝试打印所有组时,我得到 "IndexOutOfBoundsException: No group 4",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38167540/