我正在尝试学习 C++11 中的正则表达式。一定是做错了什么,因为似乎没有括号或转义序列起作用。
这是我的代码:
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main()
{
try
{
cout << R"(\d*(\.\d*)?;)" << endl << endl;
regex rx{ R"(\d*(\.\d*)?;)", regex_constants::ECMAScript };
smatch m;
if( regex_match( string( "10;20;30;40;" ), m, rx ) )
{
cout << m[0];
}
}
catch( const regex_error &e )
{
cerr << e.what() << ". Code: " << e.code() << endl;
switch( e.code() )
{
case regex_constants::error_collate:
cerr << "The expression contained an invalid collating element name.";
break;
case regex_constants::error_ctype:
cerr << "The expression contained an invalid character class name.";
break;
case regex_constants::error_escape:
cerr << "The expression contained an invalid escaped character, or a trailing escape.";
break;
case regex_constants::error_backref:
cerr << "The expression contained an invalid back reference.";
break;
case regex_constants::error_brack:
cerr << "The expression contained mismatched brackets ([ and ]).";
break;
case regex_constants::error_paren:
cerr << "The expression contained mismatched parentheses (( and )).";
break;
case regex_constants::error_brace:
cerr << "The expression contained mismatched braces ({ and }).";
break;
case regex_constants::error_badbrace:
cerr << "The expression contained an invalid range between braces ({ and }).";
break;
case regex_constants::error_range:
cerr << "The expression contained an invalid character range.";
break;
case regex_constants::error_space:
cerr << "There was insufficient memory to convert the expression into a finite state machine.";
break;
case regex_constants::error_badrepeat:
cerr << "The expression contained a repeat specifier (one of *?+{) that was not preceded by a valid regular expression.";
break;
case regex_constants::error_complexity:
cerr << "The complexity of an attempted match against a regular expression exceeded a pre-set level.";
break;
case regex_constants::error_stack:
cerr << "There was insufficient memory to determine whether the regular expression could match the specified character sequence.";
break;
default:
cerr << "Undefined.";
break;
}
cerr << endl;
}
return 0;
}
输出:
\d*(.\d*)?;
正则表达式错误。代码:2
表达式包含无效的转义字符或尾随转义。
我究竟做错了什么?
更新
gcc 版本 4.8.2 20131212 (Red Hat 4.8.2-7) (GCC)
clang 3.3 版 (tags/RELEASE_33/final)
libstdc++ 版本 4.8.2
解决方案
好。我正在阅读“C++ 编程语言”并想尝试使用 std::regex 的东西。所以我想解决方案是等待gcc-4.9。
我为 EagleV_Attnam 指出我的代码中的其他错误表示赞赏。