regex_match找不到方括号

regex_match fails to find square brackets

本文关键字:方括号 找不到 match regex      更新时间:2023-10-16

我正在尝试对一个包含方括号([...])的字符串执行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小提琴,编译器不应该成为问题即使在那里,我也没有看到regex_match发生

您遇到的主要问题是过时的gcc编译器:您需要升级到最新版本。4.8.x只是不支持regex。

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

#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演示

使用

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

它们肯定应该使用反斜杠进行转义。不幸的是,由于反斜杠本身在文字字符串中是特殊的,所以需要两个反斜杠。因此regex应该看起来像"(.*)a/b/c\[2\]/d(.*)"

原始字符串文字通常会简化必须具有复杂转义序列的情况:

#include <iostream>
#include <cstring>
#include <regex>
using namespace std;
int main () {
    std::string str1 = "a/b/c[2]/d";
    std::string str2 = R"regex((.*)a/b/c[2]/d(.*))regex";
    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;
    }
}

预期输出:

str1 = a/b/c[2]/d
str2 = (.*)a/b/c[2]/d(.*)