正则表达式计算正则表达式中捕获组的数量

问题描述:

我需要一个正则表达式来检查任意正则表达式(作为字符串),返回捕获组的数量。到目前为止,我有......

I need a regex that examines arbitrary regex (as a string), returning the number of capturing groups. So far I have...

arbitrary_regex.toString().match(/\((|[^?].*?)\)/g).length

哪些情况适用于某些情况,其中假设任何以问号开头的组都是非捕获的。它还会计算空组。

Which works for some cases, where the assumption that any group that starts with a question mark, is non-capturing. It also counts empty groups.

它不适用于字符类或转义括号中包含的括号,也可能适用于其他一些场景。

It does not work for brackets included in character classes, or escaped brackets, and possibly some other scenarios.

修改你的正则表达式,使它匹配一个空字符串,然后匹配一个空字符串,看看它返回的组数:

Modify your regex so that it will match an empty string, then match an empty string and see how many groups it returns:

var num_groups = (new RegExp(regex.toString() + '|')).exec('').length - 1;

示例: http://jsfiddle.net/EEn6G/