为什么这个正则表达式抛出异常



我试图在C++11中使用std::regex_replace(Visual Studio 2013),但我试图创建的正则表达式引发了一个异常:

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"或"\x999"其中X=A-Z或A-Z并且9=0-9。

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

(另一个问题:我可以像在最后一行那样使用backreference吗?我想根据匹配动态替换)

感谢您的帮助

根据以上注释,您需要修复正则表达式:要匹配文字反斜杠,您需要使用"\\"(或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-regex替换格式字符串,确切的语法取决于标志的值

最新更新