programmbuzz programmbuzz - 5 months ago 10
Java Question

I get "IndexOutOfBoundsException: No group 4" when I try to print all groups

I have the code as

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());
}


This code Gives the output as
abcabcd


But I want to print all the groups in the matched string i.e

group 1 abc
group 2 ab
group 3 cd


I tried this

int i=1;
while (m.group(i) != null)
{
System.out.println("group" + i + m.group(i));
i++;
}


I'm getting

group 1 abc
group 2 ab
group 3 cd
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 4


How can I avoid this exception?

Answer

The problem is when i incremented to 4, you're still checking:

m.group(i) != null

But there's no such group 4.

One solution would be using Matcher#groupCount:

while (i < m.groupCount() + 1) {
    System.out.println("group " + i + ": " + m.group(i));
    i++;
}
Comments