c++ - regex_match 找不到方括号

标签 c++ regex c++11

我正在尝试对内部有方括号( [...] )的字符串进行 regex_match 。

到目前为止我尝试过的事情:

  • 正常匹配
  • 用 1 个斜杠反斜杠方括号
  • 用 2 个斜杠反斜杠方括号

重现代码:

#include <iostream>
#include <cstring>
#include <regex>

using namespace std;

int main () {
  std::string str1 = "a/b/c[2]/d";
  std::string str2 = "(.*)a/b/c[2]/d(.*)";
  std::regex e(str2);

  std::cout << "str1 = " << str1 << std::endl;
  std::cout << "str2 = " << str2 << std::endl;
  if (regex_match(str1, e)) {
    std::cout << "matched" << std::endl;
  }
}

这是我每次编译时收到的错误消息。

terminate called after throwing an instance of 'std::regex_error'
what():  regex_error
Aborted (core dumped)

堆栈溢出成员告诉我,gcc 4.8 或更早版本已知存在错误。因此,我需要将其更新到最新版本。

我创建了一个Ideone fiddle编译器不应该出现问题的地方。 即使在那里,我也没有看到 regex_match 发生。

最佳答案

您遇到的主要问题是过时的 gcc 编译器:您需要升级到某个最新版本。 4.8.x 只是不支持正则表达式。

现在,您应该使用的代码是:

#include <iostream>
#include <cstring>
#include <regex>

using namespace std;

int main () {
    std::string str1 = "a/b/c[2]/d";
    std::string str2 = R"(a/b/c\[2]/d)";
    std::regex e(str2);

    std::cout << "str1 = " << str1 << std::endl;
    std::cout << "str2 = " << str2 << std::endl;
    if (regex_search(str1, e)) {
        std::cout << "matched" << std::endl;
    }
}

请参阅IDEONE demo

使用

  • regex_search 而不是 regex_match 来搜索部分匹配(regex_match 需要完整字符串匹配)<
  • 正则表达式模式中的 [2] 与文字 2 匹配([...] 是匹配 1 个字符的字符类字符类中指定的范围/列表)。要匹配文字方括号,您需要转义 [ 而不必转义 ]: R"(a/b/c\[2 ]/d)"

关于c++ - regex_match 找不到方括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36596563/

相关文章:

c# - 使用正则表达式以任意顺序查找两个字符串

c++ - 使类不可复制*和*不可 move

c++ - 如何以编程方式查找进程的所有文件句柄?

匹配 '|' 且前面没有 '\' 的 JavaScript 正则表达式(lookbehind 替代方案)

c# - C# 中的嵌套正则表达式替换

c++ - 在 C++ 中获取给定指向它的指针的类型名的类型名

c++ - 具有静态绑定(bind)成员函数指针的可变参数模板的多个特化?

c++ - 无法理解 C++ 引用手册中示例中使用的这种类型 `void(C::* volatile)(int) const `

c++ - 为什么隐藏符号仍然添加到 DSO

c++ - 指针 "gets informed"如何知道指向对象的哪一部分可以访问?