title: How are nested capturing groups numbered in regular expressions?
body: <p>Is there a defined behavior for how regular expressions should handle the capturing behavior of nested parentheses?  More specifically, can you reasonably expect that different engines will capture the outer parentheses in the first position, and nested parentheses in subsequent positions?</p>
  
  <p>Consider the following PHP code (using PCRE regular expressions)</p>
  
  <pre><code>&lt;?php
    $test_string = 'I want to test sub patterns';
    preg_match('{(I (want) (to) test) sub (patterns)}', $test_string, $matches);
    print_r($matches);
  ?&gt;
  
  Array
  (
      [0] =&gt; I want to test sub patterns  //entire pattern
      [1] =&gt; I want to test           //entire outer parenthesis
      [2] =&gt; want             //first inner
      [3] =&gt; to               //second inner
      [4] =&gt; patterns             //next parentheses set
  )
  </code></pre>
  
  <p>The entire parenthesized expression is captured first (I want to test), and then the inner parenthesized patterns are captured next ("want" and "to").  This makes logical sense, but I could see an equally logical case being made for first capturing the sub parentheses, and THEN capturing the entire pattern.</p>
  
  <p>So, is this "capture the entire thing first" defined behavior in regular expression engines, or is it going to depend on the context of the pattern and/or the behavior of the engine (PCRE being different than C#'s being different than Java's being different than etc.)?</p>