函数正则表达式C++在 linux(CentOS) 中遇到错误,但在 OSX 中



我尝试编写一个程序来测试C++中的正则表达式,所以我阅读并遵循标准示例,我的代码如下:

#include <stdio.h>
#include <regex>
#include <string>
using namespace std;
char var1[10] = "12345";
string var2 = "12345";
int main()
{
    if (regex_match( var1, regex( "\d+" ) ) ){
        printf("var1 matchn");
    }else{
        printf("var1 not matchn");
    }
    if (regex_match( var2, regex( "\d+" ) ) ){
        printf("var2 matchn");
    }else{
        printf("var2 not matchn");
    }
}

然后我运行如下命令进行编译和运行:

g++ retest.cpp -o retest -std=c++0x
./retest

但它向我显示以下错误:

terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Aborted

我修改了代码,最终发现错误导致正则表达式()中的常规字符串。但是当我在OSX中编写相同的代码时,它可以运行并向我显示正确的结果!我很困惑,为什么我使用标准的C++库,但在 CentOS 和 OSX 中结果不同?如何解决这个问题?谢谢!

CentOS 有相当古老的 GCC 软件包。您可以在 http://distrowatch.com/table.php?distribution=centos 中查看详细信息

在我的 CentOS 7 机器上说,

# gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE

并且,<regex>在GCC 4.9.0中实现。 https://stackoverflow.com/a/12665408/3627572

最新更新