Java 我得到;IndexOutOfBoundsException:无第4组“;当我尝试打印所有组时
我的代码是Java 我得到;IndexOutOfBoundsException:无第4组“;当我尝试打印所有组时,java,regex,Java,Regex,我的代码是 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 我试过这个 int i=1; while (m.group(i) != n
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
我试过这个
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
我怎样才能避免这个例外
如何打印所有组的开始和结束索引?问题是当
I
增加到4时,您仍在检查:
m.group(i) != null
但是没有这样的第四组
一种解决办法是使用:
while(i
您可以通过以下方式打印所有组的开始索引和结束索引
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++;
}
while(ii@rock321987正确,这是另一个选项。
while (i < m.groupCount() + 1) {
System.out.println("group " + i + ": " + m.group(i));
i++;
}
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++;
}