gpt4 book ai didi

c++ - 为什么这个正则表达式会抛出异常?

转载 作者:行者123 更新时间:2023-11-30 05:45:11 25 4
gpt4 key购买 nike

我正在尝试在 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 = A-Z 或 a-z,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 documentation 中找不到这样的功能。 :

fmt - the regex replacement format string, exact syntax depends on the value of flags

关于c++ - 为什么这个正则表达式会抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29476237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com