Script Valley
Regex: Actually Useful Patterns
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

Backreferences

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.

Up next

How to extract all matches with regex in JavaScript and Python

Sign in to track progress