Skip to content

Lesson 5 of 13 · 22m

Capture Groups, Backreferences, and Replacement

Numbered and named groups, non-capturing groups, the last-iteration trap, and the replacement syntax that differs in every tool.

Matching is a yes/no answer. Capturing is where regex earns its keep: pulling structure out of a line of unstructured text — the IP, the timestamp, the status, the path, in one pass over the line. It's also where the subtle bugs live — a group that renumbers when a teammate adds one more pair of parentheses, or a repeated group that quietly keeps only its last iteration.

Groups are numbered by their opening parenthesis

((\d{4})-(\d{2}))-(\d{2})        input: 2025-03-14
^^                ^
12    3           4

group 1 = 2025-03    group 2 = 2025    group 3 = 03    group 4 = 14

Count left parentheses from the left. Insert a group near the front and every later number shifts — which is why positional references belong in throwaway one-liners, not production code other people edit. The commit that adds a (\d{2}) to the middle of a pattern looks innocent in review; the $4 in the replacement three functions away is where it detonates.

Named groups survive refactors

const line = '203.0.113.42 - - [14/Mar/2025:09:26:53 +0000] "POST /api/v1/login HTTP/1.1" 401 112 "-" "python-requests/2.31.0"';
const re = /^(?<ip>\S+) \S+ \S+ \[(?<time>[^\]]+)\] "(?<method>[A-Z]+) (?<path>\S+) [^"]*" (?<status>\d{3}) (?<bytes>\d+|-)/;
const { ip, method, path, status } = line.match(re).groups;
console.log(ip, method, path, status);  // 203.0.113.42 POST /api/v1/login 401

Names document intent and don't shift when the pattern grows. Python spells them (?P<ip>...); JavaScript, PCRE2, Java, and .NET use (?<ip>...). Read them as m.groups (JS), m.groupdict() (Python), matcher.group("ip") (Java).

Group without capturing

(?:...) groups for alternation or a quantifier without consuming a slot number — and it fixes the most common precedence bug:

^GET|POST$          parses as (^GET) or (POST$) — matches "GET-anything" and "anything-POST"
^(?:GET|POST)$      matches exactly GET or exactly POST

Alternation has the lowest precedence in regex. When an alternation shares an anchor with something else, it almost always needs a group around it.

A repeated group keeps only its last iteration

console.log(/^(\d+\.)+\d+$/.exec("10.0.12.7")[1]);             // "12." — not all octets
console.log([..."10.0.12.7".matchAll(/\d+/g)].map(m => m[0])); // ["10", "0", "12", "7"]

Each pass through (\d+\.) overwrites the capture. If you need every repetition, iterate with a global search (matchAll, re.finditer) or capture the whole repeated span and split it.

A related trick: String.split keeps a captured delimiter in the output array. "a,b;c".split(/[,;]/) gives ["a","b","c"], but "a,b;c".split(/([,;])/) gives ["a", ",", "b", ";", "c"] — the separators survive, which is exactly what a tokenizer wants.

Backreferences and replacement

A backreference re-matches whatever the group captured. \b(\w+)\s+\1\b finds doubled words ("the the") — the lint rule that catches the typo spellcheck can't. In replacements, every tool spells it differently:

  • JavaScript: $1, $<name>, $& whole match, $$ literal dollar
  • Python: \1, \g<name>, \g<0> whole match
  • sed/awk: \1–\9, & whole match
  • Perl/PCRE2: $1, $+{name}
const iso = "2025-03-14";
console.log(iso.replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/, "$<d>/$<m>/$<y>"));  // 14/03/2025

Named backreferences exist too — (?<word>\w+)\s+\k<word> in JS/PCRE2, (?P=word) in Python. They make the doubled-word lint readable: the backreference names what it's re-matching instead of pointing at a number.

Field notes

  • An optional group that didn't participate is undefined in JS, None in Python. Template it into a string and you ship the literal text "undefined".
  • In Python, r"\10" means group 10, not group 1 plus 0. Write r"\g<1>0".
  • $ is special in JS replacement strings. If the replacement comes from user data, pass a function: s.replace(re, () => userText).
  • matchAll throws TypeError without the g flag — a feature; it stops you from looping forever.
  • ES2022's d flag adds match.indices — start/end offsets per group, which is what you want when you're re-slicing the original line.

Keep reading

Related articles from the SudoSecurity blog.