skipnothing/Regex Engines

Backreferences

Write (\w+) \1 and the engine matches the the but walks right past the cat. The second token is not the pattern \w+ running again, it is the exact word the first group already grabbed.

  • ▸\1 re-matches the text a group captured, so a backtrack that re-captures changes what it demands.
  • ▸Remembering an arbitrary captured word to recompare is what a fixed-state, single-pass engine cannot do, so it rejects \1.
  • ▸\1 fits "the same span twice" like doubled words and matched tags, never nested structure like balanced brackets.
BUILDS ON
01

The Backreference Reads the Slot

Group 1 in (\w+) \1 grabs a word and parks its span in slot 1. When the engine reaches \1, it does not run \w+ a second time. It opens slot 1, finds the stored text the, and compares that text against the input one character at a time. On the the the comparison lands; on the cat the c fails against the stored t and the whole match dies. The token \1 carries a value, the text captured on this attempt, not the rule that produced it.

SLOT 1 FILLS, THEN \1 READS IT BACK

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 11+ more topics in Regex Engines.

Sign up, it's freeSee the full Regex Engines