Some of the regular expressions are very complex and they can take lot of time to evaluate.
For instance below is a simple regular expression.
var regEx = new Regex(@"^(\d+)+$",
RegexOptions.Singleline);
If someone inputs a huge number as shown in the below code snippet. It will take more than a minute to resolve the expression leading to lot of load on the application. So we would like to give a time out on the expression. So if the validation takes more than a specific interval we would like the application to give up and move ahead.
var match =
regEx.Match("123453109839109283090492309480329489812093809x");
In .NET 4.5 we can now provide the timeout value as parameter on the constructor. For instance in the below code we have provided 2 seconds timeout on the regex (regular expression). So if it exceeds more than 2 second “regexMatchTimeOutException” will occur.
try
{
var regEx = new
Regex(@"^(\d+)+$", RegexOptions.Singleline, TimeSpan.FromSeconds(2));
var match =
regEx.Match("123453109839109283090492309480329489812093809x");
}
catch
(RegexMatchTimeoutException ex)
{
Console.WriteLine("Regex Timeout");