繁体   English   中英

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

[英]Why does this regex throw an exception?

我正在尝试在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 regex库,但是它也会引发一些误解。

(另一个问题:我可以像在最后一行中一样使用反向引用吗?我想根据匹配项进行动态替换)

谢谢你的帮助

根据以上注释,您需要修复正则表达式:要匹配文字反斜杠,您需要使用"\\\\\\\\" (或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文档中找不到这样的功能:

fmt-正则表达式替换格式字符串,确切的语法取决于flags的值

暂无
暂无

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

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