简体   繁体   English

为什么此正则表达式会引发异常?

[英]Why does this regex throw an exception?

I am trying to use std::regex_replace in C++11 (Visual Studio 2013) but the regex i am trying to create is throwing an exception: 我正在尝试在C ++ 11(Visual Studio 2013)中使用std::regex_replace ,但我尝试创建的正则表达式会引发异常:

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

Why is this the case? 为什么会这样呢? This is my definition: 这是我的定义:

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("$&"));

What i want to do: Find all matches inside a string which are of the following format: 我想做的事情:查找具有以下格式的字符串中的所有匹配项:

"\\X99" OR "\\999" where X = AZ or az and 9 = 0-9. “ \\ X99”或“ \\ 999”,其中X = AZ或az和9 = 0-9。

I also tried to use the boost regex library, but it also throws an exeception. 我也尝试使用boost regex库,但是它也会引发一些误解。

(Another question: Can i use the backreference as i am doing in the last line? I want to replace dynamically according to the match) (另一个问题:我可以像在最后一行中一样使用反向引用吗?我想根据匹配项进行动态替换)

Thanks for any help 谢谢你的帮助

As per the above comments, you need to fix your regex: to match a literal backslash you need to use "\\\\\\\\" (or R("\\\\") ). 根据以上注释,您需要修复正则表达式:要匹配文字反斜杠,您需要使用"\\\\\\\\" (或R("\\\\") )。

My code that shows all the first captured groups: 我的代码显示了所有最初捕获的组:

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();
    }

Output: 输出:

\X99
\999

Regarding using a method call inside a replacement string , I do not find such a functionality in the regex_replace documentation : 关于在替换字符串中使用方法调用,我在regex_replace文档中找不到这样的功能:

fmt - the regex replacement format string, exact syntax depends on the value of flags fmt-正则表达式替换格式字符串,确切的语法取决于flags的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM