【问题标题】:Regex program not catching exception, other problems正则表达式程序没有捕获异常,其他问题
【发布时间】:2013-10-25 18:11:53
【问题描述】:

当我运行这段代码时:

#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 4.8.1 上使用 g++(是的,我指定了 -std=c++11),并且我意识到正则表达式的东西在 4.9 之前仍然是实验性的,所以这可以解释为什么第一个捕获组是错误的以及为什么它可能第二个正则表达式有问题。我仍然担心为什么它说它正在抛出 std::regex_error 但我的代码没有捕捉到它。在 catch 子句中将 exception&amp; 更改为 regex_error&amp; 不会改变行为。所有这些都只是库错误,还是我做错了什么?在 15 年左右没有使用 C++ 之后,我正在尝试重新学习它(并且也在尝试学习 C++11),所以我担心我可能做了一些愚蠢的事情。

【问题讨论】:

    标签: c++ regex g++


    【解决方案1】:

    异常发生在这一行:

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

    而且这一行不在“Try-catch”块内。

    【讨论】:

    • 好的,谢谢。就我而言,这看起来像是一个愚蠢的错误——但另一方面,我发现的在线 C++ 参考文献甚至没有提到抛出 regex_error 的可能性,更不用说告诉我它会在什么时候被抛出,所以我真的说不出来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 2021-07-09
    • 2020-06-25
    相关资源
    最近更新 更多