c++ - 如何使用 re2 获取部分匹配的数量
问题描述
我想使用 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 因为字符串中有三个标点符号;
解决方案
使用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;
}
推荐阅读
- javascript - 如何修复 Electron.js 中的菜单和更改页面?
- ruby - ||= 和 |= 与布尔值有什么区别
- javascript - 如何在 Maven(Java)Project 中为 javascript 设置测试环境?
- node.js - 如何在 Puppeteer 中获取当前页面?
- python - BeautifulSoup - 在多个“表”上使用 find_all 时出现 AttributeError
- c# - 在c#中将自定义的单个字符串转换为JSON并根据条件构造最终的json
- scala - 如何根据 spark scala 中的匹配条件从列名中提取数字?
- c - 为什么这个while循环没有像我使用for循环那样运行两次?
- azure - 如何在 azure logic app 中处理动态 json 内容
- http - 如何在带有http的飞镖中使用mailgun添加附件?