1

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

2 回答 2

8

只需将字符串拆分为多个文字并使用 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]+);"编译器组合。这也将允许您向正则表达式添加不会被忽略的空格。然而,额外的引号会使这写起来有点费力。

于 2016-06-10T14:40:30.687 回答
5
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);

并做了。

于 2016-06-10T14:41:26.717 回答