# Number of capture groups in a regular expression in php

I am trying to find the number of capture groups for a regular expression using this PHP function.

/**
* Finds the number of groups in a regular expression
* @param $regexPatten string The regular expression * @return int Returns the number of groups inside the regular expression */ public static function numOfGroups($regexPatten)
{
$regexPatten = str_replace('\\\\', "",$regexPatten); // remove all escaped backslashes
\$regexPatten = str_replace('\$$', "", regexPatten); // remove all escaped open parentheses regexPatten = str_replace('(?:', "", regexPatten); // remove all none capture groups return substr_count(regexPatten, "("); // count the remaining opening parentheses }  And here is my test: var_dump(Parser::numOfGroups("(test)")); // 1 -- will match: test var_dump(Parser::numOfGroups("\((test)$$")); // 1  --  will match: (test)
var_dump(Parser::numOfGroups("\\\\$$(test)\\\\(\d+)$$")); // 2  --  plain regex: \\$$(test)\\(\d+)$$  --  will match: \(test\343)
var_dump(Parser::numOfGroups("((?:test(?: )?)+)")); // 1  --  will match: test test


Is there any use cases I have forgotten?

• Character sets [...(...] come to mind.
– vnp
Jun 28 '17 at 20:50
• @vnp but it can't tell if the if the open parentheses are escaped Jun 28 '17 at 20:55
• I mean you will count such ( as a capturing one.
– vnp
Jun 28 '17 at 20:56
• What are you really trying to achieve? You are trying to build a regex parser? Jun 28 '17 at 21:43
• But why? Are you expecting to get arbitrary regular expression passed to this method that you need to get metadata for? Do you really need to know this information before the regex is run (at which point you can typically easily count the number of capturing groups if there is a pattern match)? Jun 28 '17 at 22:00

(?:/*pattern*/)