简体   繁体   中英

Is it possible to count the number of capture groups in an arbitrary std::regex object?

For an arbitrary std::regex , is it possible to know the number of capture groups in it?

Assume the result will be returned by a function CountCaptures() . This is what I'd like to get:

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

I know this is possible with std::smatch after matching the string, but the thing is that I'm receiving a regex from a user and I need to constrain capture groups in a certain way before matching any strings.

You can use std::basic_regex::mark_count() .

Example usage

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';

Output:

r1 has 0 capture groups
r2 has 1 capture groups
r3 has 2 capture groups

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM