The Regex.MatchTimeout property

Posted: (EET/GMT+2)

 

Regular expressions are powerful, but a bad pattern can sometimes hang your application. This is especially relevant with long or complex input. To prevent this from happening, .NET lets you set a match timeout so the regex evaluation stops if it takes too long.

You can specify it globally for the process or per instance. For example:

var pattern = @"(\w+\s?)+";
var input = new string('a', 10000);

var regex = new Regex(pattern, RegexOptions.None, TimeSpan.FromMilliseconds(100));
try
{
    var match = regex.Match(input);
    Console.WriteLine(match.Success);
}
catch (RegexMatchTimeoutException)
{
    Console.WriteLine("Match timed out.");
}

Or set a default timeout in App.config:

<configuration>
  <runtime>
    <regex matchTimeout="00:00:02" />
  </runtime>
</configuration>

Adding a timeout is a simple way to protect against so-called “catastrophic backtracking” — where a pattern runs exponentially longer on certain inputs. It’s especially useful in web apps or any service that handles user-supplied text.