This question already has answers here:
Is gcc 4.8 or earlier buggy about regular expressions?

(3个答案)


4年前关闭。




我正在尝试对其中带有方括号([...])的字符串进行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需要完整的字符串匹配项)
  • regex模式中的[2]与文字2匹配([...]是与字符类中指定的范围/列表中的1个字符匹配的字符类)。要匹配文字方括号,您需要转义[,而不必转义]:R"(a/b/c\[2]/d)"
  • 07-24 09:44
    查看更多