C++11 match_regex与简单模式不匹配

C++11 match_regex doesn't match a simple pattern

本文关键字:简单 模式 不匹配 regex match C++11      更新时间:2023-10-16

我在C++使用新的正则表达式库时遇到了一些问题。下面是一个简单的示例:

#include<regex>
#include<string>
#include<iostream>
using namespace std;
int main(){
    string text = "123.456";
    string pattern = "[0-9]+\.[0-9]+";
    try{
        cout << (regex_match(text, regex(pattern, regex_constants::extended)) ? "Passn" : "Failn");
    }catch(...){
        cout << "Fail (bad regex)n";
    }
    return 0;
}

问题是,无论我使用哪种类型的匹配(简单,扩展,grep,egrep,awk等),它总是返回false。如果我使用"regex_constants::simple",它会抛出异常,因为不支持括号表达式,但我检查了规范,它应该可以正常工作"regex_constants::extended"。

结果如下:

rhobincu@daneel:~/work$ g++ -std=c++11 test.cpp -o test
rhobincu@daneel:~/work$ ./test 
Fail

知道我做错了什么吗?

编辑:这可能也是有用的信息:

rhobincu@daneel:~/work$ g++ --version
g++ (Ubuntu/Linaro 4.8.1-10ubuntu8) 4.8.1
Copyright (C) 2013 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的libstdc++中尚不受支持,当前状态。

您只需将std::regex替换为boost::regex,它就可以编译并正常工作。