正则表达式程序没有捕获异常,其他问题

时间:2013-10-25 18:11:53

标签: c++ regex g++

当我运行此代码时:

#include <iostream>
#include <regex>

using namespace std;

main () {
    const string source = "hello(abc_def)";
    const regex regexp("he(l)lo.*");
    smatch m;
    if (regex_match(source, m, regexp)) {
        cout << "Found, group 1 = " << m[1].str() << endl;
    } else {
        cout << "Not found" << endl;
    }
    const regex regexp2("hello\\((\\w+)\\)");
    try {
        if (regex_match(source, m, regexp2)) {
            cout << "Found, group 1 = " << m[1].str() << endl;
        } else {
            cout << "Not found" << endl;
        }
    } catch(const exception& exc) {
        cout << "Got exception: " << exc.what() << endl;
    }
}

输出是:

Found, group 1 = el
terminate called after throwing an instance of 'std::regex_error'
   what():  regex_error

伴随着程序崩溃的对话框。我在Windows上使用g ++,4.8.1(是的,我指定-std=c++11),我意识到正则表达式的东西在4.9之前仍然是实验性的,所以这可以解释为什么第一个捕获组是错误的以及为什么它可能与第二个正则表达式有问题。我仍然担心为什么它说它正在抛出std::regex_error,但我的代码没有抓住它。在exception&子句中将regex_error&更改为catch并未改变行为。所有这些只是库错误,还是我做错了什么?我试图在未使用它15年左右之后重新学习C ++(并且还试图学习C ++ 11),所以我担心我可能做了一些愚蠢的事情。

1 个答案:

答案 0 :(得分:1)

此行发生异常:

const regex regexp2("hello\\((\\w+)\\)");

此行不在“Try-catch”块中。