.NET 4.5 Baby Steps, Part 7: Regular Expression Timeouts

Submitted by Robert MacLean on Wed, 05/09/2012 - 13:02
Other posts in this series can be found on the Series Index Page


While the regular expression passing in .NET is damn fast, there are times where it can take too long for your needs. Until now there hasn’t been much you can do but wait. In .NET 4.5 we get the ability to timeout regular expressions if they took too long.


So lets look at a really silly example to start off with, checking a string fifty million characters (where only one is different) against regular expression which is looking for fifty million letters. As I said it is silly, but to get a truly slow reg ex is pretty hard.

static Regex match = new Regex(@"\w{50000000}", RegexOptions.None);
static void Main(string[] args)
    var sw = Stopwatch.StartNew();
    Console.WriteLine(match.IsMatch(String.Empty.PadRight(49999999, 'a') + "!"));

This 13.5secs on my machine!


imageAll we need to do to take advantage of the new timeouts is modify the constructor of the Regex, by adding a third parameter.

static Regex match = new Regex(@"\w{50 000 000}", RegexOptions.None, TimeSpan.FromSeconds(5));

Now after five seconds a RegexMatchTimeoutException is raised.