title: Java regex: how to back-reference capturing groups in a certain context when their number is not known in advance
body: <p>As an introductory note, I am aware of the old saying about solving problems with regex and I am also aware about the precautions on processing XML with RegEx. But please bear with me for a moment...</p>
  
  <p>I am trying to do a RegEx search and replace on a group of characters. I don't know in advance how often this group will be matched, but I want to search with a certain context only. </p>
  
  <p>An example: 
  If I have the following string <code>"**ab**df**ab**sdf**ab**fdsa**ab**bb"</code> and I want to search for <code>"ab"</code> and replace with <code>"@ab@"</code>, this works fine using the following regex: </p>
  
  <p>Search regex:</p>
  
  <pre><code>(.*?)(ab)(.*?)
  </code></pre>
  
  <p>Replace:</p>
  
  <pre><code>$1@$2@$3
  </code></pre>
  
  <p>I get four matches in total, as expected. Within each match, the group IDs are the same, so the back-references ($1, $2 ...) work fine, too. </p>
  
  <p>However, if I now add a certain context to the string, the regex above fails: </p>
  
  <p>Search string:</p>
  
  <pre><code>&lt;context&gt;abdfabsdfabfdsaabbb&lt;/context&gt;
  </code></pre>
  
  <p>Search regex:</p>
  
  <pre><code>&lt;context&gt;(.*?)(ab)(.*?)&lt;/context&gt;
  </code></pre>
  
  <p>This will find only the first match. 
  But even if I add a non-capturing group to the original regex, it doesn't work (<code>"&lt;context&gt;(?:(.*?)(ab)(.*?))*&lt;/context&gt;"</code>). </p>
  
  <p>What I would like is a list of matches as in the first search (without the context), whereby within each match the group IDs are the same.</p>
  
  <p>Any idea how this could be achieved?</p>