Regex只匹配匹配组中许多可能性中的前两个

Regex matches only the first two of many possibilities in a matching group

本文关键字:两个 可能性 许多 Regex      更新时间:2023-10-16

我注意到,c++11正则表达式只"考虑"了包含4个选项的匹配组中的前两个选项。根据regex101,regex是正确的,如果我更改匹配组中元素的顺序,前两个总是会被识别,但后面的不会被识别。代码非常简单,有没有遗漏什么?

#include <iostream>
#include <regex>
using namespace std;
int main()
{
    std::regex staticFilesMatcher(".*\.(ico|jpg|png|gif)", std::regex_constants::ECMAScript | std::regex_constants::icase);
    if (std::regex_match("test.ico", staticFilesMatcher))
        std::cout << "ICO file recognized" << std::endl;
    if (std::regex_match("test.jpg", staticFilesMatcher))
        std::cout << "JPG file recognized" << std::endl;
    if (std::regex_match("test.png", staticFilesMatcher))
        std::cout << "PNG file recognized" << std::endl;
    if (std::regex_match("test.gif", staticFilesMatcher))
        std::cout << "GIF file recognized" << std::endl;
    return 0;
}

奇怪的是,输出是

ICO file recognized
JPG file recognized
Process returned 0 (0x0)   execution time : 0.002 s
Press ENTER to continue.

感谢您的帮助,让我找到解决方案。

根据您的评论,您使用的是GCC 4.8.2。但是regex直到GCC 4.9才得以实施。如果不能升级编译器,就必须使用boost.regex