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

GroupValue
$1 / \12026
$205
$328

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=123 into userId: 123 with a capture-heavy pattern
  • Normalize dates from DD/MM/YYYY to YYYY-MM-DD by 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.

When you want to practice, use the related DevCove tool — optional, not part of this lesson.

Open related tool

Back to course overview