【问题标题】:std::regex ignore whitespace inside regex commandstd::regex 忽略正则表达式命令中的空格
【发布时间】:2016-10-11 12:58:08
【问题描述】:

我们可以使用被忽略的空格/换行符格式化 std::regex 字符串吗?只是为了更好地阅读?有没有像Python VERBOSE) 这样的选项?

不赘述:

charref = re.compile("&#(0[0-7]+"
                     "|[0-9]+"
                     "|x[0-9a-fA-F]+);")

详细说明:

charref = re.compile(r"""
 &[#]                # Start of a numeric entity reference
 (
     0[0-7]+         # Octal form
   | [0-9]+          # Decimal form
   | x[0-9a-fA-F]+   # Hexadecimal form
 )
 ;                   # Trailing semicolon
""", re.VERBOSE)

【问题讨论】:

  • 我不这么认为。您可以使用原始字符串文字并将其传递给另一个函数,该函数去除其空白,然后将其编译为正则表达式,但您必须自己编写该剥离函数。
  • 您可以将字符串文字拆分为多行,就像您在第一个示例中显示的那样。您可以在这些线上放置 cmets。

标签: c++ regex c++11 verbose


【解决方案1】:

只需将字符串拆分为多个文字并像这样使用 C++ cmets:

std::regex rgx( 
   "&[#]"                // Start of a numeric entity reference
   "("
     "0[0-7]+"           // Octal form
     "|[0-9]+"           // Decimal form
     "|x[0-9a-fA-F]+"    // Hexadecimal form
   ")"
   ";"                   // Trailing semicolon
);

然后它们将被编译器组合成"&[#](0[0-7]+|[0-9]+|x[0-9a-fA-F]+);"。这也将允许您向正则表达式添加不会被忽略的空格。然而,额外的引号会使这写起来有点费力。

【讨论】:

    【解决方案2】:
    inline std::string remove_ws(std::string in) {
      in.erase(std::remove_if(in.begin(), in.end(), std::isspace), in.end());
      return in;
    }
    
    inline std::string operator""_nows(const char* str, std::size_t length) {
      return remove_ws({str, str+length});
    }
    

    现在,这不支持# comments,但添加它应该很容易。只需创建一个从字符串中剥离它们的函数,然后执行以下操作:

    std::string remove_comments(std::string const& s)
    {
      std::regex comment_re("#[^\n]*\n");
      return std::regex_replace(s, comment_re, "");
    }
    // above remove_comments not tested, but you get the idea
    
    std::string operator""_verbose(const char* str, std::size_t length) {
      return remove_ws( remove_comments( {str, str+length} ) );
    }
    

    完成后,我们得到:

    charref = re.compile(R"---(
     &[#]                # Start of a numeric entity reference
     (
         0[0-7]+         # Octal form
       | [0-9]+          # Decimal form
       | x[0-9a-fA-F]+   # Hexadecimal form
     )
     ;                   # Trailing semicolon
    )---"_verbose);
    

    完成了。

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 2020-08-06
      • 2011-08-12
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多