Regex to count the number of capturing groups in a regex

前端 未结 2 1724
野的像风
野的像风 2020-12-29 07:10

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(/\\((         


        
相关标签:
2条回答
  • 2020-12-29 08:00

    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;
    

    Example: http://jsfiddle.net/EEn6G/

    0 讨论(0)
  • 2020-12-29 08:00

    The accepted answer is what you should use in any production system. However, if you wanted to solve it using a regex for fun, you can do that as shown below. It assumes the regex you want the number of groups in is correct.

    Note that the number of groups is just the number of non-literal (s in the regex. The strategy we're going to take is instead of matching all the correct (, we're going to split on all the incorrect stuff in between them.

    re.toString().split(/(\(\?|\\\[|\[(?:\\\]|.)*?\]|\\\(|[^(])+/g).length - 1
    

    You can see how it works on www.debuggex.com.

    0 讨论(0)
提交回复
热议问题