liveBook · Manning

Regular-expression anchor

As explained in Secrets of the JavaScript Ninja, Third Edition

An anchor is a regular-expression construct that constrains a match to a position such as the start or end of a string.

Finding a substring and checking an entire input are different jobs. An anchor makes a regular expression match at a position rather than consuming a character. Use `^` at the start of a pattern to require the beginning of the string, and `$` to require its end. section 12.2.2

Substring or whole string?

`/^test/` matches `testing`, but not `pretest`. `/test$/` matches `pretest`, but not `testing`. `/^test$/` matches only `test`: the pattern must span the entire candidate string. Anchors also work with repetition: `/^t?est$/` accepts `test` and `est`, but no extra characters. section 12.2.2 section 12.2.2

Position matters for words, too. `\b` matches the boundary between a word character and a non-word character or a string edge; it does not match a character itself. In `/\b([a-z]+) \1\b/i`, the boundaries keep the repeated-word match from picking `doki doki` out of longer adjoining words. Here `\1` refers back to the captured word. Do not confuse `^` at the start of a regex with `^` inside a character class such as `[^abc]`, where it negates the class. section 12.4.3 section 12.2.2

Anchoring an entire input does not guarantee a quick rejection. With `/^(?:\w+\s*)+$/`, a trailing `!` prevents the end anchor from matching after an otherwise plausible sequence of words. The regex can then backtrack through many ways of grouping the preceding characters; the optional whitespace adds possibilities. Check the repetition structure as well as the anchors when a full-string test runs slowly. 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`,
);

Run the timed JavaScript example to compare immediate acceptance of a word roster with slow rejection of an input ending in `!`. section 12.6.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines start, end, and word-boundary positions and traces an end anchor’s role in a backtracking failure.
Examples
Uses `test` matches, a doubled-word regex, and a timed rejection of a word sequence ending in `!`.
What you can do after
Diagnose/debug with it by distinguishing partial from whole-string matches and spotting when an anchored rejection triggers excessive backtracking.
How it connects
Connects anchors with character classes, capturing groups, backreferences, and regex backtracking.

Also explained in

Compare how 4 books explain regular-expression anchor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.