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

Why does std::regex_match not support "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不支持"zero-length assertions"?

regex_match is only for matching the entire input string. Your regex — written correctly as "^\w*uild(?=ing$) with the backslash escaped, or as a raw string 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;
}