[英]C# Regex “Verbose” like in Python
In Python, we have the re.VERBOSE
argument that allows us to nicely format regex
expressions and include comments, such as 在Python中,我们有
re.VERBOSE
参数,它使我们能够很好地格式化regex
表达式的格式并包括注释,例如
import re
ric_index = re.compile(r'''(
^(?P<delim>\.) # delimiter "."
(?P<root>\w+)$ # Root Symbol, at least 1 character
)''',re.VERBOSE)
Is there something similar in C#? C#中是否有类似的东西?
Yes, you can have comments in .NET regex. 是的,您可以在.NET正则表达式中添加注释。
(examples copied from : https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference#miscellaneous_constructs ) (示例摘自: https : //docs.microsoft.com/zh-cn/dotnet/standard/base-types/regular-expression-language-quick-reference#miscellaneous_constructs )
You can have inline comments with (?# .... )
: 您可以使用
(?# .... )
进行内联注释:
string regex = @"\bA(?#Matches words starting with A)\w+\b"
or comment to the end of line #
或注释到第
#
行的末尾
string regex = @"(?x)\bA\w+\b#Matches words starting with A"
And you can always span your regex string on several lines, and use classic C# comments : 而且,您始终可以将正则表达式字符串分成几行,并使用经典的C#注释:
string regex =
@"\d{1,3}" + // 1 to 3 digits
@"\w+" + // any word characters
@"\d{10}"; // 10 digits
See also Thomas Ayoub's answer for use of verbatim string @""
on several lines 另请参见Thomas Ayoub关于在多行上使用逐字字符串
@""
的答案
You can use verbatim string (using @
), which allow you to write: 您可以使用逐字字符串(使用
@
),该字符串允许您编写:
var regex = new Regex(@"^(?<delim>\\.) # delimiter "".""
(?<root>\\w+)$ # Root Symbol, at least 1 character
", RegexOptions.IgnorePatternWhitespace);
Note the use of RegexOptions.IgnorePatternWhitespace
option to write verbose regexes. 请注意使用
RegexOptions.IgnorePatternWhitespace
选项来编写详细的正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.