Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex "Verbose" like in Python

Tags:

python

c#

regex

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#?

like image 374
Josh D Avatar asked Nov 02 '25 04:11

Josh D


1 Answers

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.

like image 155
Thomas Ayoub Avatar answered Nov 03 '25 19:11

Thomas Ayoub