Lesson 4
Capture Groups and Replace
Grouping, backreferences, and replacement templates.
Capture groups let a regex remember parts of a match. That memory powers extraction, validation breakdowns, and structured find-and-replace.
Numbered groups
Parentheses create numbered groups left to right:
Pattern: (\d{4})-(\d{2})-(\d{2}) on 2026-05-28
| Group | Value |
|---|---|
$1 / \1 | 2026 |
$2 | 05 |
$3 | 28 |
In JavaScript replace callbacks, match[1], match[2], … hold the same values.
Non-capturing groups
When you need grouping without storing a capture, use (?: ... ):
(?:https?):// groups the scheme alternative without occupying $1.
This keeps replacement templates stable when you add optional prefixes later.
Backreferences
\1 inside a pattern refers to whatever group 1 matched. Classic example: (['"]).*?\1 matches quoted strings with the same opening and closing quote.
Backreferences are powerful and easy to misuse on nested structures—another reason not to parse HTML with regex alone.
Replacement templates
Editors and languages use $1, $2, or $& (whole match) in replace strings:
- Turn
user_id=123intouserId: 123with a capture-heavy pattern - Normalize dates from
DD/MM/YYYYtoYYYY-MM-DDby reordering groups
Always preview replacements on multiple lines, including empty fields and unexpected spacing.
Named groups (modern JavaScript)
(?<year>\d{4}) exposes match.groups.year. Named groups improve readability in long patterns.
Key takeaway
Design patterns so each capture maps to one semantic field. If your replacement string needs ten $n references, consider simplifying the pattern or using a parser instead.