Groups and CapturingLesson 2.4
Backreferences in regex to match repeated text
backreference syntax \1, named backreference \k, duplicate detection, HTML tag matching, backreference limitations
Backreferences Match What Was Already Captured
A backreference reuses what a capturing group matched earlier in the same pattern. \1 matches the same text as group 1, not the same pattern.
// Find doubled words
const doubled = /\b(\w+)\s+\1\b/gi;
'the the sky is blue blue'.match(doubled)
// => ['the the', 'blue blue']
Named Backreferences
// JavaScript
/(?<tag>\w+).*\k<tag>/.test('start...start') // true
Backreferences are best for detecting duplicate tokens, symmetric delimiters, and repeated words.
