尝试学习如何在 C++11 中使用新的 std::regex。但是我尝试的示例是抛出一个我不明白的 regex_error 异常。这是我的示例代码:
#include <iostream>
#include <regex>
int main()
{
std::string str = "xyzabc1xyzabc2xyzabc3abc4xyz";
std::regex re( "(abc[1234])" ); // <-- this line throws a C++ exception
// also tried to do this:
// std::regex re( "(abc[1234])", std::regex::optimize | std::regex::extended );
while ( true )
{
std::cout << "searching in " << str << std::endl;
std::smatch match;
std::regex_search( str, match, re );
if ( match.empty() )
{
std::cout << "...no more matches" << std::endl;
break;
}
for ( auto x : match )
{
std::cout << "found: " << x << std::endl;
}
str = match.suffix().str();
}
return 0;
}
我像这样编译和运行:
g++ -g -std=c++11 test.cpp
./a.out
terminate called after throwing an instance of 'std::regex_error'
what(): regex_error
查看 gdb 中的回溯,我看到抛出的异常是regex_constants::error_brack
.