Module 4 · Lesson 4 of 416/32 in the course~18 min
Module lessons (4/4)
Named groups and back-references
Lesson preview5 hands-on exercises readyRegex Course · Module 4 — Groups and alternation
(?<name>...) to give a name; \1 \k<name> to refer back to the capture.
What you'll learn in this lesson
- Give groups a semantic name using
(?<name>...)and read them into JS viamatch.groups.name. - Use backreferences within the same pattern with
\1(numbered) and\k<name>(named) to match identical repeating substrings. - Write real patterns to detect consecutive duplicate words (
\b(\w+)\s+\1\b) and balanced HTML/XML tag pairs. - Understanding the performance risk of backreferences inside quantifiers on uncontrolled inputs.
Overview
Counting parentheses ($1, $4, $7) in a complex pattern is fragile and hard to read. The (?<name>...) syntax binds a clear name to each capture (match.groups.year, $<year>). Furthermore, with backreferences (\1, \2 or \k<name>) you can require a subsequent portion of the text to be identical character for character to…
Sections covered in this lesson
- 1Mental model: Capture by name and backreference
- 2Progressive examples
- 3Guided laboratory
- 4Check for understanding
Pro Lesson · Module 4 — Groups and alternation
Unlock "Named groups and back-references" and the full Regex Course curriculum
`(?<name>...)` to give a name; `\1` `\k<name>` to refer back to the capture.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Regex Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.