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 = 14Count 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 401Names 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 POSTAlternation 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/2025Named 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
undefinedin JS,Nonein Python. Template it into a string and you ship the literal text "undefined". - In Python,
r"\10"means group 10, not group 1 plus0. Writer"\g<1>0". $is special in JS replacement strings. If the replacement comes from user data, pass a function:s.replace(re, () => userText).matchAllthrows TypeError without thegflag — a feature; it stops you from looping forever.- ES2022's
dflag addsmatch.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.
Java Pulled Primitive Patterns After Five Previews. JDK 28 Won't Compile Them.
Primitive types in patterns, instanceof, and switch previewed in every JDK from 23 to 27. On November 9 the Amber team withdrew the feature, and it won't be in JDK 28 even with --enable-preview. Here's why Valhalla changed the plan, what replaces it, and how to rewrite code that used it.
.NET 11 Is Out. Union Types Got the Applause, but unsafe Is What Changed.
.NET 11 shipped on November 10, 2026, and C# 15 finally has union types, the feature people have asked for since pattern matching arrived.
PHP 8.6 Finally Turns On the Session Settings You Were Told to Set in 2006
Every PHP hardening guide for two decades has told you to flip the same three session settings. PHP 8.6, due November 19, 2026, flips them for you: strict mode on, HttpOnly on, SameSite set to Lax.
Rust 1.100: The Never Type Is Finally Stable, and Cargo Learned to Wait
Rust 1.100 stabilizes the never type after ten years and five failed attempts, along with the core Allocator API and a DropGuard helper. The change most teams will notice is in Cargo: a one-line config that makes it skip any crate version published in the last few days.