我得到“IndexOutOfBoundsException: No group 4";当我尝试打印所有组时 [英] I get "IndexOutOfBoundsException: No group 4" when I try to print all groups
本文介绍了我得到“IndexOutOfBoundsException: No group 4";当我尝试打印所有组时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有代码
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
如何避免这种异常?
以及如何打印所有组的开始和结束索引?
And How can I print the starting and ending Indexes of all groups?
推荐答案
可以通过
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++;
}
这篇关于我得到“IndexOutOfBoundsException: No group 4";当我尝试打印所有组时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文