Over a million developers have joined DZone.

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

·

Introduction

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.

Problem

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') + "!"));
    sw.Stop();
    Console.WriteLine(sw.Elapsed);
    Console.ReadLine();
}

This 13.5secs on my machine!

Solution

image

All 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.

AttachmentSize
RegEx timeout demo32.73 KB
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}