std::basic_regex<CharT,Traits>::mark_count

来自cppreference.com
< cpp‎ | regex‎ | basic regex
unsigned mark_count() const;
(C++11 起)

返回正则表达式内有标记的子表达式(又称捕获组)数。

参数

(无)

返回值

正则表达式内有标记的子表达式数。

异常

可能抛出实现定义的异常。

示例

#include <iostream>
#include <regex>
 
int main()
{    
    std::regex r1{"abcde"};
    std::cout << "r1 has " << r1.mark_count() << " subexpressions" <<  '\n';
    //  期待: 0
 
    std::regex r2{"ab(c)de"};
    std::cout << "r2 has " << r2.mark_count() << " subexpressions" << '\n';
    //  期待: 1
 
    std::regex r3{"a(bc)d(e)"}; 
    std::cout << "r3 has " << r3.mark_count() << " subexpressions" << '\n';
    //  期待: 2
 
    //  嵌套的子表达式
    std::regex r4{"abc(de(fg))"};
    std::cout << "r4 has " << r4.mark_count() << " subexpressions" << '\n';
    //  期待: 2
 
    //  转义的括号
    std::regex r5{"a(bc\\(\\)de)"};
    std::cout << "r5 has " << r5.mark_count() << " subexpressions" << '\n';
    //  期待: 1
 
    //  使用 nosubs 标志
    std::regex r6 {"ab(c)de", std::regex_constants::nosubs};
    std::cout << "r6 has " << r6.mark_count() << " subexpressions" << '\n';
    //  Expected: 0
}

输出:

r1 has 0 subexpressions
r2 has 1 subexpressions
r3 has 2 subexpressions
r4 has 2 subexpressions
r5 has 1 subexpressions
r6 has 0 subexpressions