Regex to count the number of capturing groups in a regex

前端 未结 2 1737
野的像风
野的像风 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条回答
  •  梦毁少年i
    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/

提交回复
热议问题