Timeout in Regular Expressions

Regular expressions are common forms of parsing a document and get meaning. It has been very popular and most of the people do use it regularly to solve their complex problems. Being a developer, I use them very often.

But there is a catch on using a regular expression. Regular expression gives you a chance to create a string expression that works on another document. But when a document or an expression is very complex it might take a little while to give its result. It can even produce an infinite loop in certain cases which can take hell lot of time etc. Having said that, there has been always a requirement as a developer to have a timeout defined for a Regular expression while parsing the document.

In latest release of .NET framework, Regular expressions allows you to give timeout seed which will automatically break the regular expression after the certain interval is reached. Here is how you can define the same.

bool RegExIsMatch = false;
string testString = "Abhishek is a Microsoft MVP in client app dev";
string RegExPattern = @"([a-z ]+)*!";
TimeSpantsRegexTimeout tstimeout = TimeSpan.FromMilliseconds(1);
    RegExIsMatch = Regex.IsMatch(testString, RegExPattern, RegexOptions.None, tstimeout);
catch (RegexMatchTimeoutException ex)
   Console.WriteLine("Timeout specified: " + ex.MatchTimeout);

Here in the code above, we specified the timeout of 1 millisecond, which is very small. You can try the code to see a Timeout while running the expression.

The IsMatch function generates a RegexMatchTimeoutException when the patter takes too long on the document. You cannot specify TimeSpan.Zero or negetive or greater than 24 days in Timespan, because it will throw ArgumentOutOfRangeException.

I hope this will help.

Happy programming.

Subscribe To Newsletter For your Daily Development Tips and Tricks  

 Best Tips & Tricks on Microsoft Technology Platform 

Invalid email address
We promise not to spam you. You can unsubscribe at any time.
Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434