C# Regex “Verbose” like in Python

对着背影说爱祢 提交于 2021-02-16 20:28:12

问题


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<delim>\.)    # delimiter "."
    (?P<root>\w+)$    # Root Symbol, at least 1 character
    )''',re.VERBOSE)

Is there something similar in C#?


回答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.




回答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



来源:https://stackoverflow.com/questions/50683833/c-sharp-regex-verbose-like-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!