title: Determine how many capturing groups are in a javascript regexp?
body: <p>I'm working on a utility to merge multiple regular expressions into one. I want to support replace with a function, but that means I need to have an offset for the capturing groups so I can pass the correct arguments to the replacer function. Here's the simplest solution I have found:</p>
  
  <pre><code>function countCapturingGroups(regexp) {
    var count = 0;
    regexp.source.replace(/(\\*)\((\?:)?/g,
        function(full, backslashes, nonCapturing) {
      if (backslashes.length % 2 === 0 &amp;&amp; !nonCapturing) {
        count++;
      }
    });
    return count;
  }
  </code></pre>
  
  <p>This supports:</p>
  
  <ol>
  <li>Any number of backslashes (an even number means the backslash is itself escaped)</li>
  <li>Non-capturing groups, e.g. <code>/(?:this)/</code></li>
  </ol>
  
  <p>Am I overlooking any other valid ways to use parentheses that won't capture content?</p>
  
  <p>You can see it in action here: <a href="http://jsfiddle.net/theazureshadow/RHdPP/" rel="nofollow">http://jsfiddle.net/theazureshadow/RHdPP/</a></p>