2015-04-06 162 views
1

我想在C++ 11(Visual Studio中2013)使用std::regex_replace,但我想创建正则表达式时抛出异常:为什么这个正则表达式会抛出异常?

Microsoft C++ exception: std::regex_error at memory location 0x0030ED34 

为什么会出现这种情况?这是我的定义:

std::string regexStr = R"(\([A - Za - z] | [0 - 9])[0 - 9]{2})"; 

std::regex rg(regexStr); <-- This is where the exception thrown 

line = std::regex_replace(line, rg, this->protyp->getUTF8Character("$&")); 

我想要做什么:找哪家有以下几种格式的字符串中的所有匹配:

“\ X99”或“\ 999” 其中X = AZ或az和9 = 0-9。

我也尝试过使用boost正则表达式库,但它也抛出了一个怀疑。

(另一个问题:我可以用我在最后一行是做反向引用我想根据比赛动态更换)

感谢所有帮助

+1

为什么你周围的空间'-'在字符类的 价值? – Barmar

+3

您的正则表达式的问题是括号不平衡。其中一个开括号会被转义,因此与右括号不匹配。 – Barmar

+0

@puelo'\\ [A-Za-z \ d] \ d {2} \ b' –

回答

1

按照上述意见,你需要修正你的正则表达式:匹配你需要使用的文字反斜杠"\\\\"(或R("\\"))。

我的代码,显示所有捕获的第一组:

string line = "\\X99 \\999"; 
string regexStr = "(\\\\([A-Za-z]|[0-9])[0-9]{2})"; 
regex rg(regexStr); //<-- This is where the exception was thrown before 
smatch sm; 
while (regex_search(line, sm, rg)) { 
     std::cout << sm[1] << std::endl; 
     line = sm.suffix().str(); 
    } 

输出:

\X99 
\999 

使用替换字符串里面的方法调用至于,我不觉得这样的功能regex_replace documentation

FMT - 正则表达式替换格式字符串,确切语法取决于标志

相关问题