title: How to match nested repeating groups with regex in Java?
body: <p>I'm trying to match repeating groups with Java:</p>
  
  <pre><code>String s = "The very first line\n"
          + "\n"
          + "AA (aa)\n"
          + "BB (bb)\n"
          + "CC (cc)\n"
          + "\n";
  
  Pattern p = Pattern.compile(
          "The very first line\\s+"
          + "((?&lt;gr1&gt;[a-z]+)\\s+\\((?&lt;gr2&gt;[^)]+)\\)\\s*)+",
          Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
  
  Matcher m = p.matcher(s);
  
  if (m.find()) {
      for (int i = 0; i &lt;= m.groupCount(); i++) {
          System.out.println("group #" + i + ": [" + m.group(i).trim() + "]");
      }
      System.out.println("group gr1: [" + m.group("gr1").trim() + "]");
      System.out.println("group gr2: [" + m.group("gr2").trim() + "]");
  }
  </code></pre>
  
  <p>The problem is with the repeating groups: though the regex matches the whole text block (see <code>group #0</code> in output example below), when retrieving groups <code>#2</code> and <code>#3</code> (or by name as well - <code>gr1</code>/<code>gr2</code>) it does return only the last match (<code>CC/cc</code>) and skips the previous ones (<code>AA/aa</code> and <code>BB/bb</code>)</p>
  
  <pre><code>group #0: [The very first line
  
  AA (aa)
  BB (bb)
  CC (cc)]
  group #1: [CC (cc)]
  group #2: [CC]
  group #3: [cc]
  group gr1: [CC]
  group gr2: [cc]
  </code></pre>
  
  <p>Is there a way to solve this?</p>
  
  <p><strong>edit:</strong> <code>The very first line</code> is in the pattern as identification string - see the comment to the gknicker's answer below</p>