title: What is the Java regex to use back-references and capture groups correctly
body: <p>I want to strip a SOAP envelope from a message to get at the XML in the body. </p>
  
  <p>I attempted the following;</p>
  
  <pre><code>String strippedOfEnvelopedHeader = msg.replaceAll("(?s)(?i)&lt;(.*):Envelope.*&lt;\1:Body&gt;", "");
  </code></pre>
  
  <p>I thought that this would stip out the SOAP envelope, specifically the header, from a message like;</p>
  
  <p><code>
  &lt;soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'&gt;<br/>
     &lt;env:Header xmlns:env='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'/&gt;<br/>
     &lt;soapenv:Body&gt;<br/>
          &lt;myXML&gt; stuff is here&lt;/myXML&gt;<br/>
     &lt;/soapenv:Body&gt;<br/>
  &lt;/soapenv:Envelope&gt;
  </code></p>
  
  <p>which should result in;</p>
  
  <p><code>
          &lt;myXML&gt; stuff is here&lt;/myXML&gt;<br/>
     &lt;/soapenv:Body&gt;<br/>
  &lt;/soapenv:Envelope&gt;
  </code></p>
  
  <p>However, the group back-reference does not seem to work.</p>
  
  <p>If I replace both the capture group and the back-reference the substitution works fine;</p>
  
  <pre><code>String strippedOfEnvelopeHeader = msg.replaceAll("(?i)(?s)&lt;soapenv:Envelope.*&lt;soapenv:Body&gt;", "");
  </code></pre>
  
  <p>I think I can guess the problem, the capture group is being greedy and grabbing the entire message and thus failing the match.</p>
  
  <p>But the solution evades me.</p>
  
  <p>Any ideas?</p>