首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用RE2::FindAndConsumeN的无限循环

使用RE2::FindAndConsumeN的无限循环
EN

Stack Overflow用户
提问于 2015-05-05 16:21:46
回答 2查看 621关注 0票数 2

我正在尝试计算一个模式在表达式中出现的次数:

代码语言:javascript
复制
while (RE2::FindAndConsumeN(&stringPiece, regex, nullptr, 0))
{
    ++matches;
}

使用以下命令进行测试:

代码语言:javascript
复制
auto stringPiece = RE2::StringPiece("aaa");
auto regexp = RE2::re2("a*");

最终循环永远运行(我希望它返回1),有人知道我是怎么使用它的吗?

谢谢

EN

回答 2

Stack Overflow用户

发布于 2015-05-05 16:28:14

TL;DR findAndConsume的查找失败,因为它找不到输入开头的内容。失败意味着找到匹配是,但我猜它不能正确移动缓冲区,导致无限循环。

根据header of re2的说法:

代码语言:javascript
复制
  // Like Consume(..), but does not anchor the match at the beginning of the
  // string.  That is, "pattern" need not start its match at the beginning of
  // "input".  For example, "FindAndConsume(s, "(\\w+)", &word)" finds the next
  // word in "s" and stores it in "word".

输入模式,即“

”不需要在“的开头开始匹配

在您的代码中,您的模式是在输入的开头匹配的,因此出现了错误的行为。

如果你给findAndConsume提供类似这样的东西:

代码语言:javascript
复制
auto stringPiece = RE2::StringPiece("baaa");

你的循环中应该不会再有错误了。

或者,如果您愿意,也可以直接使用ConsumeN():

代码语言:javascript
复制
  // Like FullMatch() and PartialMatch(), except that pattern has to
  // match a prefix of "text", and "input" is advanced past the matched
  // text.  Note: "input" is modified iff this routine returns true.
  static bool ConsumeN(StringPiece* input, const RE2& pattern, // 3..16 args
                       const Arg* const args[], int argc);
票数 1
EN

Stack Overflow用户

发布于 2015-05-05 16:28:03

如果找到了模式,我不会在while循环中调用它,因为你的模式和源代码不会改变。

这可能会在调用函数时对您有所帮助:

代码语言:javascript
复制
re2::RE2::Arg match;
re2::RE2::Arg* args[] = { &match };
re2::RE2::FindAndConsumeN(NULL, pattern, args, 1);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30047699

复制
相关文章

相似问题

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