【问题标题】:How to get number of partial matches using re2如何使用 re2 获取部分匹配的数量
【发布时间】:2019-10-18 11:07:10
【问题描述】:

我想使用 re2 获取给定字符串的子字符串匹配数;

我已经阅读了 re2:https://github.com/google/re2/blob/master/re2/re2.h 的代码,但没有看到一个简单的方法来做到这一点。

我有以下示例代码:

std::string regexPunc = "[\\p{P}]"; // matches any punctuations; 
re2::RE2 re2Punc(regexPunc);
std::string sampleString = "test...test";
if (re2::RE2::PartialMatch(sampleString, re2Punc)) {
    std::cout << re2Punc.numOfMatches();
}

我希望它输出 3,因为字符串中有三个标点符号;

【问题讨论】:

    标签: c++ re2


    【解决方案1】:

    使用FindAndConsume,并自己计算匹配项。这不会是低效的,因为为了知道匹配的数量,无论如何都必须执行和计算这些匹配。

    例子:

    std::string regexPunc = "[\\p{P}]"; // matches any punctuations; 
    re2::RE2 re2Punc(regexPunc);
    std::string sampleString = "test...test";
    StringPiece input(sampleString);
    int numberOfMatches = 0;
    while(re2::RE2::FindAndConsume(&input, re2Punc)) {
        ++numberOfMatches;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-08
      • 2023-01-31
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2021-09-28
      • 2018-04-06
      • 1970-01-01
      相关资源
      最近更新 更多