我正在尝试计算一个模式在表达式中出现的次数:
while (RE2::FindAndConsumeN(&stringPiece, regex, nullptr, 0))
{
++matches;
}使用以下命令进行测试:
auto stringPiece = RE2::StringPiece("aaa");
auto regexp = RE2::re2("a*");最终循环永远运行(我希望它返回1),有人知道我是怎么使用它的吗?
谢谢
发布于 2015-05-05 16:28:14
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".输入模式,即“
”不需要在“”的开头开始匹配
在您的代码中,您的模式是在输入的开头匹配的,因此出现了错误的行为。
如果你给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-05 16:28:03
如果找到了模式,我不会在while循环中调用它,因为你的模式和源代码不会改变。
这可能会在调用函数时对您有所帮助:
re2::RE2::Arg match;
re2::RE2::Arg* args[] = { &match };
re2::RE2::FindAndConsumeN(NULL, pattern, args, 1);https://stackoverflow.com/questions/30047699
复制相似问题