Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to count the number of capturing groups in a regex

Tags:

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.

like image 433
Billy Moon Avatar asked Apr 16 '13 20:04

Billy Moon


People also ask

What are capturing groups in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .

Can you count with regex?

To count a regex pattern multiple times in a given string, use the method len(re. findall(pattern, string)) that returns the number of matching substrings or len([*re. finditer(pattern, text)]) that unpacks all matching substrings into a list and returns the length of it as well.

What is first capturing group in regex?

First group matches abc. Escaped parentheses group the regex between them. They capture the text matched by the regex inside them into a numbered group that can be reused with a numbered backreference. They allow you to apply regex operators to the entire grouped regex.

What is matching group in regex?

Regular expressions allow us to not just match text but also to extract information for further processing. This is done by defining groups of characters and capturing them using the special parentheses ( and ) metacharacters. Any subpattern inside a pair of parentheses will be captured as a group.


1 Answers

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/

like image 172
Andrew Clark Avatar answered Sep 28 '22 04:09

Andrew Clark