2

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

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

测试它:

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

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

谢谢

4

2 回答 2

1

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


根据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".

也就是说,“模式”不必在“输入”的开头开始匹配

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

如果您提供 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);
于 2015-05-05T08:28:14.027 回答
0

RE2::FindAndConsumeN 如果找到模式,则返回一个布尔值,我不会在 while 循环中调用它,因为您的模式和源不会改变。

这可以帮助您调用函数:

re2::RE2::Arg match;
re2::RE2::Arg* args[] = { &match };
re2::RE2::FindAndConsumeN(NULL, pattern, args, 1);
于 2015-05-05T08:28:03.333 回答