【问题标题】:Is it possible to count the number of capture groups in an arbitrary std::regex object?是否可以计算任意 std::regex 对象中的捕获组数?
【发布时间】:2019-06-06 07:22:49
【问题描述】:

对于任意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

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

【问题讨论】:

    标签: c++ regex c++11 c++14 capture-group


    【解决方案1】:

    您可以使用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';
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 2011-05-24
      • 1970-01-01
      相关资源
      最近更新 更多