Class Act

Back to the shelf

C# · Method · ASP.net

Regex match timeout, stop a runaway pattern

C# code to run a regular expression with a time limit so a bad pattern on a long input does not freeze the request.

Example

How to use Regex match timeout, stop a runaway pattern:
Paste the code into the class or page, then call it from the method that needs the result.

Notes

The timeout constructor requires .NET 4.5 or later. Catch RegexMatchTimeoutException and treat it as no match.

Code

// using System.Text.RegularExpressions;
Regex rx = new Regex(@"^\d+$", RegexOptions.None, TimeSpan.FromMilliseconds(250));
bool ok = false;
try
{
    ok = rx.IsMatch(text);
}
catch (RegexMatchTimeoutException)
{
    ok = false;
}