I get "IndexOutOfBoundsException: No group 4" when I try to print all groups
<p>I have the code as</p>

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

<p>This code Gives the output as  <pre>abcabcd</pre></p>

<p>But I want to print all the groups in the matched string i.e</p>

<pre><code>group 1 abc
group 2 ab
group 3 cd
</code></pre>

<p>I tried this </p>

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

<p>I'm getting</p>

<pre><code>group 1 abc
group 2 ab
group 3 cd
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 4
</code></pre>

<p>How can I avoid this exception?</p>

<p>And How can I print the starting and ending Indexes of all  groups?</p>