【发布时间】: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& 更改为 regex_error& 不会改变行为。所有这些都只是库错误,还是我做错了什么?在 15 年左右没有使用 C++ 之后,我正在尝试重新学习它(并且也在尝试学习 C++11),所以我担心我可能做了一些愚蠢的事情。
【问题讨论】: