title: Java replaceAll with backreferences
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8604286/string-replaceall-anomaly-with-greedy-quantifiers-in-regex">String.replaceAll() anomaly with greedy quantifiers in regex</a>  </p>
  </blockquote>
  
  
  
  <p>I was writing code that uses <code>Matcher#replaceAll</code> and found following result highly confusing:</p>
  
  
  
  <pre class="lang-java prettyprint-override"><code>Pattern.compile("(.*)").matcher("sample").replaceAll("$1abc");
  </code></pre>
  
  <p>Now, I would expect the output to be <code>sampleabc</code> but Java throws at me <code>sampleabcabc</code>.</p>
  
  <p>Does anybody have any ideas why?</p>
  
  <p>Now, sure, when I anchor the pattern (<code>^(.*)$</code>) the issue goes away. Still I don't know why the hell would <code>replaceAll</code> do a double replacement like that.</p>
  
  <p>And to add insult to injury, following code:</p>
  
  <pre class="lang-java prettyprint-override"><code>Pattern.compile("(.*)").matcher("sample").replaceFirst("$1abc")
  </code></pre>
  
  <p>works as expected, returning just <code>sampleabc</code>.</p>