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 import re ric_index = re.compile(r'''( ^(?P
Solution 1:
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.
Solution 2:
Yes, you can have comments in .NET regex.
(examples copied from : https://docs.microsoft.com/en-us/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 :
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
Post a Comment for "C# Regex "verbose" Like In Python"