首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何使用re2获取部分匹配的数量

如何使用re2获取部分匹配的数量
EN

Stack Overflow用户
提问于 2019-06-03 03:10:55
回答 1查看 168关注 0票数 3

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

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

我有以下示例代码:

代码语言:javascript
代码运行次数:0
运行
复制
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,因为字符串中有三个标点符号;

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-03 03:41:23

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

示例:

代码语言:javascript
代码运行次数:0
运行
复制
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;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56418122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档