在c ++下面的regex不起作用。你能解释一下原因吗?

时间:2017-05-04 03:37:57

标签: c++ regex c++11

下面是使用正则表达式匹配字符串但不起作用的C ++程序。我的操作系统是Ubuntu Linux,编译器是ubuntu附带的标准C ++编译器。

#include <iostream>
#include <regex>

using namespace std;

int main() {
    const char s[] = "This is a target string";
    regex e ("^([0-9a-zA-Z]*).*?");
    cmatch matches;
    if(regex_match(s, matches, e)) {
        cout << "Match found" << endl;
        for (int i = 0; i < matches.size(); ++i) {
            cout << matches[i] << endl;
        }
    }
    return 0;
}

使用下面的g ++进行编译

g++ -o test test.cpp -std=c++11

使用以下输出

运行程序失败
terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
[1]    24898 abort (core dumped)  ./test

模式工作正常,我在rubular.com中尝试过。我希望它能够打印

Match Found
This is a target string
This

我不熟悉在C ++中使用正则表达式。请指出我正确的方向。

1 个答案:

答案 0 :(得分:0)

你可以使用try / catch并捕获regex_error并打印e.what()以了解出了什么问题。

顺便说一句,它与我的gcc与c ++ 11标志完美配合

catch (const std::regex_error& e) {
        std::cout << "regex_error caught: " << e.what() << '\n';
        if (e.code() == std::regex_constants::error_brack) {
            std::cout << "The code was error_brack\n";
        }
    }
相关问题