When a regular expression contains a repetition operator, how much should that operator consume? By default, it is greedy: it first takes as many consecutive matching characters as it can. That choice is tentative, because later terms in the pattern must still match. section 12.2.2 section 12.6.3
Two adjacent bracketed strings
Against `<Ninjas><Unite!>`, `/<.*>/` matches the entire string: `.*` continues past the first `>`. Append `?` to the repetition operator to make it nongreedy. `/<.*?>/` matches only `<Ninjas>`, consuming just enough to reach a match. section 12.2.2
Greedy does not mean the first choice is final. For `/[1-9][0-9]*\s+[a-z]+s/` against `27 dresses`, `[a-z]+` initially consumes `dresses`. The final `s` then has nothing left to match, so the engine backtracks one character: `[a-z]+` keeps `dresse`, and `s` matches the last character. On a longer word whose only `s` occurs early, the engine must give back characters repeatedly before it can resolve the match. 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`,
);
This timed JavaScript example contrasts a quickly accepted string with an input that is slow to reject under a pattern with repeated terms. It illustrates why backtracking behavior matters when assessing regex performance. section 12.6.3



