title: Extract capture group matches from regular expressions? (or: where is gregexec?)
body: <p>Given a regular expression containing <a href="http://www.regular-expressions.info/brackets.html" rel="noreferrer">capture groups</a> (parentheses) and a string, how can I obtain <em>all</em> the substrings matching the capture groups, i.e., the substrings usually referenced by "\1", "\2"?</p>
  
  <p>Example: consider a regex capturing digits preceded by "xy":</p>
  
  <pre><code>s &lt;- "xy1234wz98xy567"
  
  r &lt;- "xy(\\d+)"
  </code></pre>
  
  <p>Desired result:</p>
  
  <pre><code>[1] "1234" "567" 
  </code></pre>
  
  <p>First attempt: <code>gregexpr</code>:</p>
  
  <pre><code>regmatches(s,gregexpr(r,s))
  #[[1]]
  #[1] "xy1234" "xy567" 
  </code></pre>
  
  <p>Not what I want because it returns the substrings matching the entire pattern.</p>
  
  <p>Second try: <code>regexec</code>:</p>
  
  <pre><code>regmatches(s,regexec("xy(\\d+)",s))
  #[[1]]
  #[1] "xy1234" "1234" 
  </code></pre>
  
  <p>Not what I want because it returns <em>only</em> the first occurence of a matching for the entire pattern and the capture group.</p>
  
  <p>If there was a <code>gregexec</code> function, extending <code>regexec</code> as <code>gregexpr</code> extends <code>regexpr</code>, my problem would be solved.</p>
  
  <p>So the question is: how to retrieve all substrings (or indices that can be passed to <code>regmatches</code> as in the examples above) matching capture groups in an arbitrary regular expression?</p>
  
  <p>Note: the pattern for <code>r</code> given above is just a silly example, it must remain arbitrary.</p>