title: Java String.replaceAll() with back reference
body: <p>There is a Java Regex question: 
  Given a string, if the "*" is at the start or the end of the string, keep it, otherwise, remove it.
  For example:</p>
  
  <ol>
  <li><code>*</code> --> <code>*</code></li>
  <li><code>**</code> --> <code>**</code></li>
  <li><code>*******</code> --> <code>**</code></li>
  <li><code>*abc**def*</code> --> <code>*abcdef*</code></li>
  </ol>
  
  <p>The answer is:</p>
  
  <pre><code>str.replaceAll("(^\\*)|(\\*$)|\\*", "$1$2");
  </code></pre>
  
  <p>I tried the answer on my machine and it works. But I don't know how it works.</p>
  
  <p>From my understanding, all matched substrings should be replaced with <code>$1$2</code>. However, it works as:</p>
  
  <ol>
  <li><code>(^\\*)</code> replaced with <code>$1</code>,</li>
  <li><code>(\\*$)</code> replaced with <code>$2</code>,</li>
  <li><code>\\*</code> replaced with empty.</li>
  </ol>
  
  <p>Could someone explain how it works? More specifically, if there is <code>|</code> between expressions, how <code>String.replaceAll()</code> works with back reference?</p>
  
  <p>Thank you in advance.</p>