【问题标题】:std::regex throws Microsoft C++ exception: std::regex_error at memory location on runtimestd::regex 在运行时在内存位置抛出 Microsoft C++ 异常:std::regex_error
【发布时间】:2018-12-20 20:53:21
【问题描述】:

在过去的两个小时里,我试图理解为什么下面的代码行

std::regex matchPattern{R"(?<=\@)(.*?)(?=\=)"};

抛出 Microsoft C++ 异常:std::regex_error at memory location ....

我已经使用在线工具和 notepad++ 测试了正则表达式,一切正常。当我尝试在我的 c++ 应用程序中使用它时,我在初始化时从上面收到运行时错误。 我正在使用 c++14

提前感谢您的帮助。

【问题讨论】:

  • 我试过这个并没有收到任何错误。如果发布了minimal reproducible example,则可能会复制错误。
  • 它是否适用于std::regex matchPattern("^[^@[]*");?请注意,您不需要在字符类中转义 [
  • 对不起,伙计们。错误地我添加了错误的正则表达式......(我想我有点累了:))。我在最初的问题中更新了正则表达式
  • C++ std::regex 不支持lookbehind。可能您想要 R"(@([^=]+))" 并获取 Group 1 值。请分享您的代码。见this C++ demo

标签: regex c++11


【解决方案1】:

C++14 std::regex(任何它的风格)不支持lookbehind 构造。

您可以使用 R"(@([^=]+))" 并获取 Group 1 值。请注意,R"()" 是原始字符串文字边界,@([^=]+) 是匹配 @ 然后匹配并捕获除 = 之外的 1+ 个字符到组 1 中的真实字符串模式。

this C++ demo:

#include <regex>
#include <string>
#include <iostream>
using namespace std;

int main() {
    std::regex matchPattern(R"(@([^=]+))");
    std::string s("@test=boundary");
    std::smatch matches;
    if (std::regex_search(s, matches, matchPattern)) {
        std::cout<<matches.str(1);
    }
    return 0;
}

输出:

test

【讨论】:

  • 我使用 "\\" 斜杠技巧 const std::regex reg_off_p("\\+[0-9A-F]{2}");
猜你喜欢
  • 2013-08-03
  • 2015-06-03
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
  • 2010-09-13
  • 2017-08-03
  • 1970-01-01
  • 2021-10-02
相关资源
最近更新 更多