繁体   English   中英

std::regex 忽略正则表达式命令中的空格

[英]std::regex ignore whitespace inside regex command

我们可以使用被忽略的空格/换行符格式化 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)

只需将字符串拆分为多个文字并使用 C++ 注释,如下所示:

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]+);" 由编译器。 这也将允许您向正则表达式添加不会被忽略的空格。 但是,额外的引号会使编写起来有点费力。

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);

并完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM