c++ (c++ 11)正则表达式在OS X和Linux上的差异

C++ (C++11) regular expressions differences on OS X and Linux

本文关键字:c++ Linux OS 正则表达式      更新时间:2023-10-16

我试图让我的代码在OS X和Linux上工作相同。下面的代码是用clang++ --std=c++11 regextest.cpp

编译的
#include <regex>
#include <iostream>
int main()
{
    std::string str = "/api/asd/";
    std::string pattern = "/api/(.*)/";
    std::cout << "Starting matching" << std::endl;
    std::smatch matches;
    if (std::regex_match(str, matches, std::regex(pattern, std::regex::egrep)))
    {
        std::cout << "Found match!" << std::endl;
        std::cout << "All matches: ";
        for (auto& it : matches)
            std::cout << it << ", ";
        std::cout << std::endl;
    }
    return 0;
}

在OS X上,运行此代码的结果是:

Starting matching
Found match!
All matches: /api/asd/, asd,

另一方面,在Linux上(Gentoo, libstdc++ 3.3)

Starting matching
Found match!
All matches: /api/asd/, /asd/, //

如何匹配Linux上的/api/ ?为什么?

此外,尝试使用像/api/([^/])这样的模式在Linux中完全失败,在OS x中没有匹配,但工作得很好

我已经尝试了许多匹配类型的组合,(基本,扩展,grep, egrep, awk)与转义和未转义的()(取决于匹配类型),没有在Linux上产生预期的结果。

按照注释的建议,这个问题已经通过将gcc升级到4.9解决了。