title: Backreference in R
body: <p>I got really confused about the usage of backreferences</p>
  <pre><code>strings &lt;- c(&quot;^ab&quot;, &quot;ab&quot;, &quot;abc&quot;, &quot;abd&quot;, &quot;abe&quot;, &quot;ab 12&quot;)
  
  gsub(&quot;(ab) 12&quot;, &quot;\\1 34&quot;, strings)
  [1] &quot;^ab&quot;   &quot;ab&quot;    &quot;abc&quot;   &quot;abd&quot;   &quot;abe&quot;   &quot;ab 34&quot;
  
  gsub(&quot;(ab)12&quot;, &quot;\\2 34&quot;, strings)
  [1] &quot;^ab&quot;   &quot;ab&quot;    &quot;abc&quot;   &quot;abd&quot;   &quot;abe&quot;   &quot;ab 12&quot;
  </code></pre>
  <p>I know \1 refers to the first subpattern (reading from the left), \2 refers to the second subpattern, and so on. But I dont know what this subpattern means. Why \1 and \2 give different output</p>
  <pre><code>gsub(&quot;(ab)&quot;, &quot;\\1 34&quot;, strings)
  [1] &quot;^ab 34&quot;   &quot;ab 34&quot;    &quot;ab 34c&quot;   &quot;ab 34d&quot;   &quot;ab 34e&quot;   &quot;ab 34 12&quot;
  </code></pre>
  <p>Also, why I remove 12 after (ab) then it gives such result?</p>
  <pre><code>gsub(&quot;ab&quot;, &quot;\\1 34&quot;, strings)
  [1] &quot;^ 34&quot;   &quot; 34&quot;    &quot; 34c&quot;   &quot; 34d&quot;   &quot; 34e&quot;   &quot; 34 12&quot;
  </code></pre>
  <p>Furthermore, what if ab has no parenthesis? What does it indicate?</p>
  <p>I really messed up with backreference and hope someone could explain the logic clearly</p>