是否可以计算任意 std::regex 对象中的捕获组数?

The*_*ist 1 c++ regex capture-group c++11 c++14

对于任意std::regex,是否可以知道其中的捕获组数?

假设结果将由函数返回CountCaptures()。这就是我想得到的:

std::regex r1("(a)bc");
int i = CountCaptures(r1); // returns 1
std::regex r2("(a)(b)c");
int j = CountCaptures(r2); // returns 2
std::regex r3("abc");
int k = CountCaptures(r3); // returns 0
Run Code Online (Sandbox Code Playgroud)

我知道std::smatch在匹配字符串之后这是可能的,但问题是我从用户那里收到一个正则表达式,我需要在匹配任何字符串之前以某种方式限制捕获组。

Tre*_*edJ 5

您可以使用std::basic_regex::mark_count().

示例用法

std::regex r1{"abcde"};
std::cout << "r1 has " << r1.mark_count() << " capture groups" <<  '\n';

std::regex r2{"ab(c)de"};
std::cout << "r2 has " << r2.mark_count() << " capture groups" << '\n';

std::regex r3{"abc(de(fg))"};
std::cout << "r3 has " << r3.mark_count() << " capture groups" << '\n';
Run Code Online (Sandbox Code Playgroud)

输出:

r1 has 0 capture groups
r2 has 1 capture groups
r3 has 2 capture groups
Run Code Online (Sandbox Code Playgroud)