【问题标题】:Why does this regex throw an exception?为什么这个正则表达式会抛出异常?
【发布时间】:2015-04-06 17:28:22
【问题描述】:

我试图在 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 正则表达式库,但它也会引发异常。

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

感谢您的帮助

【问题讨论】:

  • 为什么在字符类中- 周围有空格?
  • 你的正则表达式的问题是括号不平衡。左括号之一被转义,因此它与右括号不匹配。
  • @puelo \\[A-Za-z\d]\d{2}\b

标签: c++ regex exception c++11


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多