
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Documenting Your Regular Expressions
|
589
However, this modified expression matches a zip code found anywhere within a
string (including a string containing just a zip code):
\d{5}(-\d{4})?
Use the regular expressions in this recipe and modify them to suit your needs.
See Also
Two good books that cover regular expressions are Regular Expression Pocket Refer-
ence and Mastering Regular Expressions, Second Edition (both from O’Reilly).
10.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";
When using this expression in a Regex object, the RegexOptions.Ignore-
PatternWhitespace
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..."); ...