Skip to content

[regex]

regex.backtracking

Decides whether a regular expression may use the backtracking engine. You set it in nvs.toml as the key backtracking in the block [regex].

Most patterns run on a linear engine. Its time grows only with the length of the text. Lookaround checks the text before or after a position, such as (?<=a). A backreference matches the same text as an earlier group, such as \1. Both need the backtracking engine. On some input, that engine can take a very long time.

There are three values:

  • allow runs these patterns on the backtracking engine. This is the default.
  • warn does the same, and the compiler prints a warning for each such pattern it finds.
  • deny does not allow these patterns at all.

With deny, a pattern written directly in Core\Regex::compile does not compile. A pattern built while the program runs throws a RuntimeError at the call that uses it. Patterns without lookaround and backreferences run as usual with every value.

A program cannot change this setting. Core\Config::set('regex.backtracking', 'allow') does not compile. When the name is in a variable, set returns false.

The example runs a simple pattern, then catches the error from a pattern with lookaround.

Only nvs.toml sets this key. A request may not change it.

A change in the file takes effect a few seconds after you save it. The server does not restart.

The examples below run with this configuration file.

nvs.toml
# A pattern that needs the backtracking engine does not compile or throws an error.
[regex]
backtracking = "deny"

A server that allows no backtracking

<?nvs
// Shows a server where every regular expression must run in linear time.
class Patterns
{
public static function after(string $prefix): string
{
return '(?<=' . $prefix . ')[0-9]+';
}
}
// This pattern has no lookaround and no backreference, so it runs as usual.
// This prints "matched".
echo Core\Regex::matches('order-42', '^order-[0-9]+$') ? 'matched' : 'no match', "\n";
// This pattern is built while the program runs. It uses lookaround,
// and `nvs.toml` sets `backtracking` to `deny`, so the call throws an error.
try {
Core\Regex::compile(Patterns::after('order-'));
echo "compiled\n";
} catch (RuntimeError $error) {
echo $error->message, "\n";
}
Output
matched
Core\Regex::compile(): `(?<=order-)[0-9]+` needs the backtracking regex engine. `[regex] backtracking` is `deny` in `nvs.toml`. Write the pattern without lookaround and without backreferences.