regex re 2-Match/PartialMatch/FindAndConclusion之间的不同行为

cpjpxq1n  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(129)

我正在使用re 2库查找文本中的正则表达式匹配。我可以看到Match()/PartialMatch()/FindAndConsume()之间的行为有所不同-在下面的代码中,只有Match()返回true并填充子匹配字符串。
如果我将正则表达式改为捕获组,即(\\d+)而不是\\d+,则所有三个函数都成功并填充子匹配。
我在re 2头文件中找不到任何有关此行为的文档。有人能解释一下为什么PartialMatch()/FindAndConsume()需要捕获组,而Match()不需要吗?

std::string text = "b123";
    re2::StringPiece sp(text);
    RE2 regex("\\d+");

    re2::StringPiece submatch;
    bool ret = regex.Match(sp, 0, text.size(), RE2::UNANCHORED, &submatch, 1); //returns true and fills submatch

    ret = RE2::PartialMatch(sp, regex, &submatch); //fails

    while (RE2::FindAndConsume(&sp, regex, &submatch)) { //fails
        std::cout << submatch << std::endl;
    }
e0bqpujr

e0bqpujr1#

re2标头中针对PartialMatchFindAndConsume的注解指出,
您的代码提供了一个指针&submatch。你的正则表达式\d+没有子模式,因此总是失败。正则表达式(\d+)有一个子模式,因此可以成功处理输入文本。
PartialMatch()FindAndConsume()不提供检索整个正则表达式匹配的方法,而不将整个正则表达式 Package 在捕获组中。
如果你传递nsubmatch >= 1Match()会用整个正则表达式匹配填充submatch[0]。如果传递nsubmatch >= 1 + NumberOfCapturingGroups(),则使用子模式的匹配项填充submatch[1]..submatch[NumberOfCapturingGroups()]Match()的头注解没有显式声明它用整个正则表达式匹配填充submatch[0]。但从这个例子和它表明1 + NumberOfCapturingGroups()nsubmatch的最大合理值的事实可以推断出这一点。

相关问题