- Jun 21, 2002
Compiling Regular Expressions
.NET uses a nondeterministic finite automation (NFA) engine to parse and analyze regular expressions. This approach is consistent with the regular expression engine found in Perl 5. The NFA engine is used by default, but if you initialize a Regex object with the RegexOptions.Compiled option your regular expression will converted and compiled to a .NET equivalent. Compiled regular expression code runs noticeably faster than code that uses the NFA engine. How much faster in a practical application is something that you can experiment with. If your application is running hundreds or thousands of expressions, such as in a search engine, it may be worthwhile to compile the regular expressions.
Additionally, you can use an emitterpart of .NET Reflectionto emit a custom regular expression class to a dynamic assembly. The final section of this article demonstrates how to use the Regex.CompileToAssembly static method to emit regular expressions to an external assembly.