Via*_*rus 1 c++ regex verbose c++11
我们可以格式化带有空格/换行符的std :: regex字符串吗?它会被忽略-只是为了更好地阅读?有没有像Python VERBOSE一样可用的选项?
不冗长:
charref = re.compile("&#(0[0-7]+"
"|[0-9]+"
"|x[0-9a-fA-F]+);")
Run Code Online (Sandbox Code Playgroud)
冗长:
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)
Run Code Online (Sandbox Code Playgroud)
只需将字符串拆分为多个文字,并使用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
);
Run Code Online (Sandbox Code Playgroud)
然后,它们将被"&[#](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});
}
Run Code Online (Sandbox Code Playgroud)
现在,这不支持# 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} ) );
}
Run Code Online (Sandbox Code Playgroud)
完成后,我们得到:
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);
Run Code Online (Sandbox Code Playgroud)
并做了。
| 归档时间: |
|
| 查看次数: |
556 次 |
| 最近记录: |