JavaScript reads cat|category against the text category and answers cat. A matcher that follows POSIX answers category. Neither one is broken. They follow different rules, and the rules come from two different ways of turning a pattern into a program. The same split decides whether ^(a+)+$ locks up a browser tab or finishes at once, and it is why the Regex Tester declines to run some patterns at all.

Which match wins: cat|category in two engines

Put cat|category in the Regular expression field and type category as the text to test. The match report reads:

1 match
#1: cat [0–3]

Reports and traces in this article follow the tool's report format.

JavaScript, like Perl, uses leftmost-first matching. It tries alternatives in the order they are written, and the first one that leads to an overall match wins, even if a later alternative would have matched more text. Swap the alternatives to category|cat and the report becomes:

1 match
#1: category [0–8]

The POSIX standard (IEEE Std 1003.1, chapter 9) uses leftmost-longest matching instead. Among the matches that start at the leftmost possible position, the longest one wins, so the order of alternatives does not matter.

One path at a time, or every path at once

The rule follows from how an engine runs a pattern. Automaton simulation carries every possible position in the pattern forward at the same time. Russ Cox gives the cost as O(m·n) for a pattern of length m and a text of length n. The engine never guesses, so it never has to undo a guess.

Backtracking tries one alternative at a time. If a choice later fails, the engine rewinds to the last decision point and tries the next option. Trying options in written order is exactly what produces leftmost-first results.

Take a(b|bc)d against the text abcd:

Backtracking
  a   matches "a"            position 1
  b   tries first branch     position 2
  d   expects "d", sees "c"  fail -> rewind to the alternation
  bc  tries second branch    position 3
  d   matches "d"            success, match [0–4]

Automaton simulation
  after "a":   {in branch b, in branch bc}
  after "b":   {expecting d, expecting c}
  after "c":   {expecting d}          (branch b dies here)
  after "d":   {accept}               match [0–4]

Both find the same match. The automaton never revisits a character, while the backtracker rewinds to position 1 and reads b and c twice.

An automaton is not tied to the POSIX rule. Go's regexp package is automaton-based, yet by default it returns the match a backtracking implementation would have chosen. It offers leftmost-longest matching separately, through CompilePOSIX.

Approach Time guarantee Backreferences and lookaround Examples
Automaton simulation (Thompson NFA, DFA) Linear in text length for a fixed pattern Not supported Thompson's 1968 compiler, RE2, Go's regexp
Backtracking Exponential in the worst case Supported Perl, PCRE, JavaScript

The ECMAScript specification defines JavaScript's pattern semantics through Matchers and continuations. Each piece of the pattern tries to match and, on success, hands over to the rest. On failure, the previous choice point gets its next chance. That is backtracking written as a specification. The V8 team, whose engine runs in Chrome and Node.js, describes its default engine, Irregexp, as a backtracking engine.

Diagnose a pattern that freezes the tab

Consider ^(a+)+$ against a run of 24 as followed by !:

aaaaaaaaaaaaaaaaaaaaaaaa!

The $ can never match because of the !, so the answer is "no match". A backtracking engine cannot know that until it has tried every way the inner a+ and the outer + can divide the run of as: one group of 24, two of 12, 23 and 1, and so on. A run of n characters can be split in 2^(n−1) ways, so each extra a roughly doubles the work. An automaton simulation handles the same input in one pass.

Cox measured a related family, a?ⁿaⁿ: n optional as followed by n required ones, matched against n as. In his test, Perl needed over sixty seconds for a 29-character string, while his Thompson NFA implementation stayed in the microsecond range.

The OWASP description of ReDoS (regular expression denial of service) lists the shapes to look for:

  • nested quantifiers, such as (a+)+
  • quantified alternation whose branches overlap, such as (a|aa)+
  • a repeated group that starts with .*, such as (.*a){x}, where several .* can each claim the same characters

The common thread is that the same stretch of text can be consumed along many different paths through the pattern. The last shape is a close relative of a real outage. On 2 July 2019, a new rule in Cloudflare's web application firewall contained a regex with the fragment .*(?:.*=.*). According to the Cloudflare postmortem, it exhausted the CPU on every core serving HTTP and HTTPS traffic, and visitors received 502 errors for 27 minutes. Davis and colleagues' ESEC/FSE 2018 study found super-linear regexes to be widespread in the npm and pip ecosystems, including in heavily reused modules.

What the Regex Tester refuses, and what it lets through

The Regex Tester runs your pattern on your browser's native RegExp engine, so it inherits that engine's backtracking. Before compiling, it runs a risk check. The check is syntactic: it reads the text of the pattern, not the automaton. It refuses a group with no parentheses inside it that contains an unbounded quantifier (+, * or {n,}) and is itself followed by one, with the message "This pattern contains nested unbounded quantifiers and may cause excessive backtracking. Simplify it before running." That catches (a+)+$ and (a*){2,}, and lets (cat|dog)+ through.

A syntactic check cannot be exact in either direction. It misses overlapping alternation like (a|a)+, which has no inner quantifier but still lets the engine split the input in many ways. It can also refuse patterns that do not blow up. (a+b)+ is refused even though each repetition must end in a b, which leaves only one way to divide the input. Telling these cases apart reliably means analysing the compiled automaton for multiple paths over the same text, not inspecting characters.

The other guards are size limits. The pattern may have up to 500 characters and the test text up to 100,000. The tool stops after 500 matches and shows a warning. At that point the Matches found counter shows 500, not the real total, so on large text read it as "500 or more".

The table lists at most 200 rows, counting match rows and group rows together, and at most 50 capture groups are reported per match. JavaScript only exposes where each capture group starts and ends when the d flag is set, so the tester adds d internally, when the engine supports it, to fill the start and end columns in Matches and capture groups.

Remove the ambiguity, or use an engine that cannot backtrack

The most direct fix is to make each character consumable in only one way. ^(a+)+$ and ^a+$ match exactly the same strings, and so do (a|aa)+ and a+. The shorter forms give a backtracker nothing to retry. When a group is needed for capturing, put the repetition either outside it or inside it, never in both places.

Other engines remove the problem by design. Google's RE2 gives up the features that need backtracking. Its syntax reference marks backreferences and lookaround as not supported. Go's regexp package follows the same design and states that it is guaranteed to run in time linear in the size of the input. After its outage, Cloudflare committed to switching to the re2 or Rust regex engine for the same reason.

PCRE2 takes a middle path. Possessive quantifiers (a++) and atomic groups ((?>...)) forbid backtracking into part of a pattern, and the library exposes limits on matching work and depth. According to pcre.org, PCRE was written by Philip Hazel for the Exim mail server. JavaScript accepts neither possessive quantifiers nor atomic groups.

In January 2021 the V8 team described an experimental non-backtracking engine that runs alongside Irregexp. Behind the command-line flag --enable-experimental-regexp-engine, V8 accepts a non-standard l flag that sends a single regex to the linear engine. A separate option, --enable-experimental-regexp-engine-on-excessive-backtracks, falls back to it after excessive backtracking. The linear engine does not handle backreferences, lookaround, large bounded repetitions such as a{200,500}, or the u and i flags. Ordinary JavaScript in a browser still runs on a backtracking engine, so in a web page, rewriting the pattern is the fix you control.

If a pattern is slow or matches the wrong text for other reasons, our article on why a regex matches too much, too little or nothing covers diagnosis.

Patterns copied from grep or another dialect

POSIX defines Basic and Extended syntax (BRE and ERE) and bracket classes such as [[:digit:]]. JavaScript has no such classes. Inside a JavaScript character class, [:digit:] is just the set of characters :, d, i, g and t, so [[:digit:]] copied from grep becomes that set plus [, followed by a literal ]. Without the u flag, the pattern still compiles but matches something else, with no error. With u, the stray ] is a syntax error. In JavaScript, write \d or [0-9] instead. Both cover only the ASCII digits 0 to 9.

Within JavaScript itself, the tester's Flags checkboxes offer only g, i, m, s, u and y. You cannot set d (match indices, ES2022) or v (set notation, ES2024; editions per TC39's finished proposals). Other syntax, such as lookbehind, depends on the browser running the page. MDN's regular expressions guide has compatibility tables.

Positions, emoji and the lastIndex cursor

JavaScript strings are sequences of UTF-16 code units. Most emoji are stored as a surrogate pair of two units, and every index a RegExp reports counts units, so an emoji spans two positions. All offsets in the tester are zero-based with an exclusive end, in the form [start–end].

This matters most for empty matches. When match, replace or matchAll hit a global match of length zero, the spec's AdvanceStringIndex moves lastIndex forward by one code unit, or by a whole code point under u or v. Only in that mode does it never land inside a surrogate pair. That mode matches requirement RL1.7 of Unicode Technical Standard #18, which asks for a surrogate pair to be handled as a single code point. A hand-written exec loop has to move lastIndex itself, or it returns the same empty match forever.

The tester's own loop advances the same way: by one unit, or by two for a surrogate pair under u. With (?:) and the flags g and u on the text 😀, the two empty matches sit at offsets 0 and 2. Without u, an empty match can land at offset 1, between the halves of the pair.

With g or y, a RegExp carries state in lastIndex. Each exec starts there and moves it to the end of the match. The sticky flag y turns "start searching at" into "match exactly at", and MDN notes that for exec, a regex with both flags behaves like a sticky one. Here is \d with the flags g and y on 12a34:

lastIndex 0: "1" matches  -> [0–1], lastIndex = 1
lastIndex 1: "2" matches  -> [1–2], lastIndex = 2
lastIndex 2: "a" is not a digit -> no match, loop ends

2 matches; "3" and "4" are never reached

With g alone, the same pattern finds all four digits.

How a 1951 notation ended up running on backtracking

The automaton design came first. The * in \d* is called the Kleene star, after Stephen Kleene. His RAND research memorandum RM-704 (1951) defined "regular events" with three operations: union (a|b), concatenation (ab) and an iteration operator, today written as the unary star (a*). Everything else is shorthand: a+ is aa*, a? is a| (a or nothing), and [abc] is a|b|c. His central result, now called Kleene's theorem, is that regular events are exactly what a finite automaton recognises.

In June 1968 Ken Thompson published "Regular Expression Search Algorithm" in Communications of the ACM. It described a compiler that translated a pattern into IBM 7094 machine code for the QED editor. The compiled code simulated a nondeterministic automaton by keeping the whole set of possible states and reading each character once. Cox notes that Thompson's work led to ed and grep, but those programs did not use the set-of-states algorithm. They used recursive backtracking instead. Over the following decades, most widely used libraries settled on backtracking too.

Backtracking made popular features easy to implement:

  • Backreferences: (\w+) \1 matches a doubled word such as the the.
  • Lookahead and lookbehind: \d+(?= EUR) matches a number only when EUR follows, without consuming it.
  • Lazy quantifiers: .*? prefers the shortest extension and grows only when forced to. They are easy to express in a backtracker, though RE2 and Go show they also work in linear-time engines.

Backreferences cross a theoretical line. A finite automaton cannot remember an arbitrary earlier substring, so (a*)b\1 describes a language that no finite automaton recognises. Patterns with backreferences are no longer regular in Kleene's sense, and Cox states that matching them is NP-complete. Supporting backreferences and lookaround is why these engines stay backtracking, and so keep the exponential worst case even for patterns that use neither.

Privacy

Matching happens in your browser's built-in RegExp engine. The page states that no text is uploaded or stored, and the pattern and test text are not sent anywhere for processing.

FAQ

Are regular expressions in programming languages still "regular" in the mathematical sense?

Not always. Patterns built only from alternation, concatenation, repetition and their shorthands can be recognised by a finite automaton. Backreferences such as \1 describe languages no finite automaton can recognise, and Cox notes that matching them is NP-complete.

Why doesn't JavaScript simply switch to a linear-time engine like RE2?

JavaScript has to support everything the spec allows, including backreferences, lookahead and lookbehind, and RE2-style engines leave those out. V8's experimental linear engine has similar gaps and is an opt-in alongside the backtracking engine, not a replacement.

Will the same pattern find the same matches in grep, Python and JavaScript?

Not reliably. grep follows POSIX leftmost-longest rules and bracket classes. Cox lists Python among the backtracking engines, like JavaScript, but syntax and flags still differ, so test a pattern in the engine where it will run.

Can I make ^(a+)+$ safe in JavaScript without changing what it matches?

For the matched strings, yes. ^a+$ matches the same strings with a single path through each input, and the tester accepts it. It drops capture group 1, though. If you need the capture, use ^(a+)$, which the tester also accepts. JavaScript has no possessive quantifiers or atomic groups, so removing the nested repetition is the practical fix.

Does the u flag change the reported offsets?

No. Offsets stay in UTF-16 code units, so an emoji still counts as two. The u flag changes how the pair is treated during matching and when stepping past empty matches.

Further reading