A regular expression can reject a short string and still do a surprising amount of work. This console experiment runs (a+)+$ against progressively longer runs of a followed by a single b, then repeats the longest input with an explicit match timeout.
The complete program targets .NET 10, uses only the base class library, and was compiled and run in a pinned Linux SDK container with networking disabled. It asserts the failed matches, the default timeout, an actual timeout exception, and two nonbacktracking controls. For a gentler introduction to matching, try our regex golf tutorial.
Why a nearly matching string is expensive
The inner a+ consumes a run of letters; the outer + permits repeated groups. The trailing b defeats the end anchor. Backtracking can repartition the same run among those groups, trying many unsuccessful paths. Microsoft documents the exponential worst case for nested quantifiers and uses this exact unanchored pattern in its backtracking and timeout example. The pattern here has no start anchor; each fixed test input nevertheless cannot match because its last character is b.
This is a deliberately expensive local demonstration. Keep the input sizes fixed and run it outside a request handler. The first loop intentionally has no timeout; stop the process if you need to abandon the experiment. Do not extend the unbounded loop to arbitrary lengths.
Run the complete experiment
With the .NET 10 SDK installed, create a console project:
dotnet new console --framework net10.0 --name RegexBacktracking
cd RegexBacktracking
Replace Program.cs with this complete program. Each length in the array counts only the letters a; the total input length includes the trailing b. The timing table goes to standard error so that standard output contains only deterministic assertion messages.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
internal static class Program
{
private static void Main()
{
const string pattern = "(a+)+$";
int[] lengths = { 10, 14, 18, 22, 26 };
var unbounded = new Regex(pattern);
Require(unbounded.MatchTimeout == Regex.InfiniteMatchTimeout,
"This isolated demo expects no application-wide timeout.");
Require(unbounded.IsMatch("aaa"), "Positive control must match.");
Console.WriteLine("PASS default MatchTimeout is InfiniteMatchTimeout");
double first = 0;
double last = 0;
Console.Error.WriteLine("a_count total_length elapsed_ms matched");
foreach (int length in lengths)
{
string input = new string('a', length) + "b";
var watch = Stopwatch.StartNew();
bool matched = unbounded.IsMatch(input);
watch.Stop();
Require(!matched, "Trailing b must prevent a match.");
double elapsed = watch.Elapsed.TotalMilliseconds;
if (length == lengths[0]) first = elapsed;
last = elapsed;
Console.Error.WriteLine(FormattableString.Invariant(
$"{length} {input.Length} {elapsed:F3} {matched}"));
}
Console.WriteLine("PASS all five trailing-b inputs fail to match");
Require(last > first, "Expected longest case to take longer than shortest.");
Console.WriteLine("PASS longest case took longer than shortest");
string longest = new string('a', lengths[^1]) + "b";
TimeSpan timeout = TimeSpan.FromSeconds(1);
var bounded = new Regex(pattern, RegexOptions.None, timeout);
Require(bounded.MatchTimeout == timeout, "Explicit timeout was not retained.");
bool timedOut = false;
try
{
_ = bounded.IsMatch(longest);
}
catch (RegexMatchTimeoutException error)
{
Require(error.MatchTimeout == timeout && error.Input == longest &&
error.Pattern == pattern, "Timeout details did not match the operation.");
timedOut = true;
}
Require(timedOut, "Expected RegexMatchTimeoutException on this runtime.");
Console.WriteLine("PASS one-second match throws RegexMatchTimeoutException");
var nonBacktracking = new Regex(pattern, RegexOptions.NonBacktracking, timeout);
Require(!nonBacktracking.IsMatch(longest) && nonBacktracking.IsMatch("aaa"),
"NonBacktracking controls returned unexpected results.");
Console.WriteLine("PASS NonBacktracking rejects trailing b and accepts aaa");
}
private static void Require(bool condition, string message)
{
if (!condition)
throw new InvalidOperationException(message);
}
}
Run it in the terminal:
dotnet run
The terminal displays a table headed a_count total_length elapsed_ms matched, with one row per input. All match results must be False. The standard-output assertions are exactly:
PASS default MatchTimeout is InfiniteMatchTimeout
PASS all five trailing-b inputs fail to match
PASS longest case took longer than shortest
PASS one-second match throws RegexMatchTimeoutException
PASS NonBacktracking rejects trailing b and accepts aaa
In the verification run, every successive table row took longer than the previous row. No elapsed-time values are prescribed here: hardware, load, runtime optimizations and build settings affect them. The program asserts only that the longest case took longer than the shortest. A small timing table illustrates this failure mode; it is not a benchmark or proof of an asymptotic bound.
The positive control aaa succeeds before timing begins. Input construction, formatting and console writes sit outside each measured match. The build reported zero warnings and zero errors, and standard output matched the five assertion lines exactly.
What the timeout assertion proves
The three-argument constructor receives the pattern, RegexOptions.None, and TimeSpan.FromSeconds(1). The test requires a RegexMatchTimeoutException and checks its pattern, input and timeout. A normal False result fails that assertion. On a different runtime or sufficiently faster machine, this fixed input might finish before timing out; a failed assertion means the reproduction did not meet its stated outcome there.
Regex.MatchTimeout is an approximate limit for a single matching operation. The engine checks time periodically and throws at a check after the interval expires. It is not a strict wall-clock deadline for the entire program or regex construction. The property is read-only; select its value when constructing the instance.
The first assertion expects InfiniteMatchTimeout from the constructor without a timeout. That holds in this fresh console process. An application-wide REGEX_DEFAULT_MATCH_TIMEOUT setting can change the default, as the default-timeout rules explain; do not assume every host has an infinite default.
Bound the work and remove unnecessary backtracking
The final check keeps the same pattern and timeout while selecting RegexOptions.NonBacktracking. It rejects the trailing-b input and accepts aaa. Microsoft describes this mode as proportional to input length for supported patterns; constructs such as lookarounds and backreferences are excluded. See the nonbacktracking guidance. These two Boolean checks do not test capture-history equivalence or establish a speedup.
For a service, treat outside patterns and inputs as untrusted. Choose an explicit matching timeout, limit accepted input sizes, and decide how the caller handles an abandoned match. This demonstration stops after its expected exception; it does not retry the same costly input. A timeout alone does not make arbitrary pattern construction safe. For broader caller policy, read timeouts, retries and cancellation as separate policies; for the catch syntax, see exception handling in C#.