O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.13. Documenting Your Regular Expressions

Problem

You have one or more complex regular expressions that may exist in a file outside of your code. You need a way to place comments within the regular expression itself. These comments will aid others in being able to read and maintain your regular expressions later on.

Solution

Add comments to the regular expression using the # comment character:

string matchPattern = @"\\\\                 # Find this:  \\
                        (?<TheServer>\w*)    # Server name
                        \\                   # Find this:  \
                        (?<TheService>\w*)\\ # Service name";

or add C#-style comments outside of the regular expression string:

string matchPattern = @"\\\\" +                // Find this:  \\
                      @"(?<TheServer>\w*)" +   // Server name
                      @"\\" +                  // Find this:  \
                      @"(?<TheService>\w*)\\"; // Service name

When using these expressions in a Regex object, the RegexOptions.IgnorePatternWhitespace enumeration value must be added to the options parameter of the Regex object constructor:

Regex RE = new Regex(matchPattern, 
  RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
MatchCollection theMatches = RE.Matches("The source text goes here...");

Discussion

With large and complex regular expressions, it is desirable to break up the expression into manageable pieces and to identify what each piece does. For example, the regular expression in the Solution section will pull the server and service pieces out of a UNC string. By breaking up the regular expression onto separate lines and adding comments to each line, we have allowed other developers (who ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required