Stop a JavaScript regex with a fuel budget: a work limit, not a timer.
dotnet add package RecursiveAI.OneEcmaRequires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.
using RecursiveAI.OneEcma.RegExp; var code = RegExpProgram.Compile("^(a+)+$", flags: ""); if (code.Program is not { } regex) return; var input = new string('a', 30) + "!"; var result = regex.Exec(input, startIndex: 0, sticky: false, fuel: new FuelMeter(1024)); Console.WriteLine(result.Outcome); Console.WriteLine(result.Limit);
LimitExceeded Fuel
Unzip the example, then dotnet run.
The full program
The full example uses the same nested-quantifier pattern on a match, an ordinary failure and thirty a characters followed by !. Each call gets fresh fuel and a backtrack-memory budget.
using RecursiveAI.OneEcma.RegExp; var compiled = RegExpProgram.Compile("^(a+)+$", ""); if (compiled.Program is not { } regex) { foreach (var error in compiled.Diagnostics) Console.WriteLine(error.Message); return; } foreach (string input in new[] { "aaaa", "bbb", new string('a', 30) + "!" }) { var fuel = new FuelMeter(1024); var result = regex.Exec(input, 0, false, fuel, new RegExpLimits { MaxBacktrackBytes = 64 * 1024 }); Console.WriteLine($"{input}: {result.Outcome} ({result.Limit})"); if (result.Match is { } match) Console.WriteLine($" Whole match: [{match.GetGroupStart(0)},{match.GetGroupEnd(0)})"); }
aaaa: Match (None) Whole match: [0,4) bbb: NoMatch (None) aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!: LimitExceeded (Fuel)
Bad patterns return compile diagnostics; exhausted execution budgets return LimitExceeded, not NoMatch.
Variations
Reject a malformed pattern before matching. The pattern is a body string, without slash delimiters:
using RecursiveAI.OneEcma.RegExp; var compiled = RegExpProgram.Compile("(", "u"); foreach (var error in compiled.Diagnostics) Console.WriteLine(error.Message);
Invalid regular expression: /(/u: Unterminated groupRelated recipes
- Check JavaScript syntax in C# without running it
- Extract JavaScript module imports in C#
- Inspect JavaScript lexical scopes in C#
The short answer
Compile a JavaScript pattern with RegExpProgram.Compile, check whether Program exists, then call Exec with a finite FuelMeter. Inspect Outcome before using Match. LimitExceeded means the search stopped before it could establish a match or a complete failure; Limit tells you whether fuel or backtrack memory stopped it.
This is the standalone JavaScript regex API in OneEcma, not a call to the .NET regular-expression engine. You can use it directly without creating a JavaScript realm or evaluating a script.
Is regex CPU-intensive?
A pattern can perform substantial matching work even on a short input. In the full example, ^(a+)+$ can divide a run of a characters among repeated groups in multiple ways. The final ! prevents the complete match, so the matcher explores alternatives until it establishes failure or hits a budget.
The example makes that distinction visible. aaaa matches, bbb produces NoMatch, and the longer near-match produces LimitExceeded with Fuel. A stopped search must not be displayed as “the input does not match.” Your application should expose an indeterminate or budget-exhausted result instead.
OneEcma charges fuel for instruction steps, backtracking and characters consumed by repeated single-character atoms. These are abstract work units. Do not turn the fuel number into a claim about CPU cycles, milliseconds or request latency. The regex documentation defines exactly what the meter measures.
How do I set a JavaScript regex timeout in C#?
The finite meter here limits work; it is not a millisecond timeout. Exec accepts a FuelMeter, not a TimeSpan. Choose a finite budget and handle exhaustion as a normal result. The sample uses 1024 units to make the exhausted case easy to reproduce, not as a universal production allowance.
For hosts that need cancellation or wall-clock checks too, the documented extension point is a FuelMeter subclass overriding TryConsume. Refusing a request stops the matcher with a limit result. The matcher draws fuel in chunks, so the extension point is not a callback for every character. It does not by itself impose an elapsed-time deadline on pattern compilation.
A meter carries remaining state and is not thread-safe. The full example creates one per input, keeping one expensive match from consuming another input’s allowance. Sharing one deliberately instead would make it an aggregate budget. Be explicit about which policy your service needs.
What are regex timeout best practices?
Handle compilation and execution separately. Compilation diagnostics mean there is no valid program to execute. Execution returns one of three outcomes: Match, NoMatch or LimitExceeded. Only the first has a match object. Keep the failure kind when logging or returning a result so users can distinguish invalid syntax from exhausted resources.
Bound backtrack memory as well as fuel. Pass RegExpLimits.MaxBacktrackBytes; the full example chooses a 64 KiB budget. This controls the matcher’s backtrack stack, not every allocation in the application. The documented default is 64 MiB if you do not supply a different limit.
Finally, understand state when building a repeated search. The low-level caller owns global searching and lastIndex; startIndex and sticky are explicit inputs to Exec. Match group offsets are UTF-16 indices, and unmatched groups use -1. The example reads only group zero after a successful match. It does not retry with an unlimited meter when a budget is exhausted.