
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Compiling Regular Expressions
|
575
See Also
See Recipe 2.6; see the “.NET Framework Regular Expressions” topic in the MSDN
documentation.
10.8 Compiling Regular Expressions
Problem
You have a handful of regular expressions to execute as quickly as possible over
many different strings. Performance is of the utmost importance.
Solution
The best way to do this task is to use compiled regular expressions. However, there
are some drawbacks to using this technique, which we will examine.
There are two ways to compile regular expressions. The easiest way is to use the
RegexOptions.Compiled enumeration value in the Options parameter of the static
Match or Matches methods on the Regex class:
Match theMatch = Regex.Match(source, pattern, RegexOptions.Compiled);
MatchCollection theMatches = Regex.Matches(source, pattern, RegexOptions.Compiled);
If more than a few expressions will be compiled and/or the expressions need to be
shared across applications, consider precompiling all of these expressions into their
own assembly. Do this by using the static
CompileToAssembly method on the Regex
class. The following method accepts an assembly name and compiles two simple reg-
ular expressions into this assembly:
public static void CreateRegExDLL(string assmName)
{
RegexCompilationInfo[] RE = new RegexCompilationInfo[2] ...