A regex engine interprets a pattern by moving through text and changing states. With greedy quantifiers, it may save consumed characters as choices, then backtrack when a later part of the pattern fails. section 12.6.3
Greedy matching can backtrack
In `/[1-9][0-9]*\s+[a-z]+s/`, matching `27 dresses` first lets `[a-z]+` consume `dresses`. Since the final `s` cannot then match, the engine gives back the last character; the pattern succeeds with `dresse` followed by `s`. section 12.6.3
Listing 12.13 A regex with catastrophic backtracking
const rosterRegex = /^(?:\w+\s*)+$/; #A
console.assert( #B
rosterRegex.test("Hattori Yoshi Fuma"), #B
"A genuine roster is accepted instantly", #B
); #B
const attack = #C
"I will erase your existence from this realm!"; #C
const start = performance.now(); #C
rosterRegex.test(attack); #C
const elapsed = performance.now() - start; #C
console.log(
`Rejecting the attack string took ${elapsed.toFixed(0)}ms`,
);
A roster-matching regex and attack string illustrate how nested repetition can make rejection take seconds. section 12.6.3

