正则表达式计算正则表达式中捕获组的数量 [英] Regex to count the number of capturing groups in a regex

查看:182
本文介绍了正则表达式计算正则表达式中捕获组的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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/

这篇关于正则表达式计算正则表达式中捕获组的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆