为什么 std::regex_match 不支持 "zero-length assertions" ?


#include <regex>
int main()
{
    b = std::regex_match("building", std::regex("^w*uild(?=ing$)"));
    //
    // b is expected to be true, but the actual value is false.
    //
}

我的编译器是 clang 3.8。

为什么 std::regex_match 不支持"零长度断言"?

regex_match仅用于匹配整个输入字符串。您的正则表达式 - 正确编写为反斜杠转义的"^\w*uild(?=ing$),或原始字符串R"(^w*uild(?=ing$))" - 仅实际匹配(使用(前缀build 。它会提前查找ing$,并将成功找到它,但由于整个输入字符串未被使用,因此regex_match拒绝匹配。

如果要使用 regex_match 但只捕获第一部分,则可以使用 ^(w*uild)ing$(或仅使用 (w*uild)ing,因为必须匹配整个字符串(并访问第一个捕获组。

但是,既然您无论如何都使用^$,因此您不妨改用regex_search:

int main()
{
    std::cmatch m;
    if (std::regex_search("building", m, std::regex(R"(^w*uild(?=ing$))"))) {
        std::cout << "m[0] = " << m[0] << std::endl;  // prints "m[0] = build"
    }
    return 0;
}

最新更新