gpt4 book ai didi

c++ - 无限循环与 RE2::FindAndConsumeN

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:18:27 28 4
gpt4 key购买 nike

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

while (RE2::FindAndConsumeN(&stringPiece, regex, nullptr, 0))
{
++matches;
}

测试它:

auto stringPiece = RE2::StringPiece("aaa");
auto regexp = RE2::re2("a*");

以永远运行的循环结束(我预计它会返回 1)有谁知道我怎么用错了?

谢谢

最佳答案

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


根据 header of re2 :

  // 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".

That is, "pattern" need not start its match at the beginning of "input"

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

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

auto stringPiece = RE2::StringPiece("baaa");

你的循环中应该没有更多的错误。

或者,如果你愿意,你可以使用 ConsumeN() 代替:

  // 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);

关于c++ - 无限循环与 RE2::FindAndConsumeN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30047699/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com