Named Groups and Replacement
Give groups readable names, use captured text in search-and-replace with $1 and named references, and transform text with replacement functions.
Welcome back!
Step 1 of 13Learn
Groups with names
Numbered groups are fragile and hard to read. In (\d{4})-(\d{2})-(\d{2}), is group 2 the month or the day? You have to count parentheses. Named groups label each capture:
(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})In JavaScript, the names appear on the result's groups object:
const m = "2026-03-14".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
m.groups.year; // "2026"
m.groups.month; // "03"Python uses a slightly different spelling, (?P<year>\d{4}), and you read the value with m.group("year"). Newer Python versions also accept the (?<year>...) form, but the P version works everywhere.
Named groups are still numbered too, so older code keeps working. But code that uses names doesn't break when someone adds another group, and the pattern documents itself: a reader sees "year," "month" and "day" instead of three anonymous \d groups. For any pattern with more than one or two captures, names are worth the extra characters.
You can also refer back to a named group inside the pattern: \k<word> in JavaScript and (?P=word) in Python are named backreferences.
Step 2 of 13Compare
Numbered vs. named groups
| Aspect | Numbered | Named |
|---|---|---|
| Pattern | (\d{4})-(\d{2}) | (?<year>\d{4})-(?<month>\d{2}) |
| Read in JavaScript | m[1], m[2] | m.groups.year |
| Replacement | $1 | $<year> |
| Add a group in front | Every later number shifts | Names stay the same |
Step 3 of 13Practice · True or false
Adding a new capturing group at the start of a pattern changes the numbers of the later groups but not their names.
Step 4 of 13Learn
Search and replace with captures
Regex shows its full power in replace operations, where captured text can be reused in the replacement. In JavaScript's replace and in most editors, $1, $2 and so on insert group values, and $<name> inserts a named group:
"2026-03-14".replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
// "03/14/2026"
"Okafor, Ben".replace(/(?<last>\w+), (?<first>\w+)/, "$<first> $<last>");
// "Ben Okafor"Other useful tokens in JavaScript replacements: $& inserts the whole match, and $$ inserts a literal dollar sign.
Python uses backslashes instead: re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\2/\3/\1", text), with \g<name> for named groups. Editors vary: VS Code uses $1, while some tools use \1. The concept is identical.
Remember the global flag. In JavaScript, replace with a regex lacking g replaces only the first match. To reformat every date in a document, use /.../g or the replaceAll method, which requires the g flag when given a regex.
Step 5 of 13Practice · Diagram
One replace, step by step
Which step decides the new order of year, month and day?
Tap the shape that answers the question, then press Check.
- Text: 1999-12-31
- (\d{4})-(\d{2})-(\d{2}) matches
- $1 = 1999, $2 = 12, $3 = 31
- Replacement "$2/$3/$1"
- Result: 12/31/1999
Step 6 of 13Practice · Match the pairs
In JavaScript, match each replacement string to the result of "2026-03-14".replace(/(\d{4})-(\d{2})-(\d{2})/, ...).
Tap an answer, then tap the place where it belongs (or drag it there).
- "$3.$2.$1"
- "$1/$2"
- "[$&]"
- "$2-$3"
Step 7 of 13Learn
Replacement functions
Sometimes the replacement needs logic, not just rearranging: converting units, changing case, or looking values up. Both JavaScript and Python let you pass a function instead of a replacement string. The function receives the match and returns the replacement text.
In JavaScript, the function's arguments are the whole match followed by each group:
const text = "Prices: 10 EUR, 25 EUR";
text.replace(/(\d+) EUR/g, (whole, amount) => {
return Math.round(Number(amount) * 1.08) + " USD";
});
// "Prices: 11 USD, 27 USD" (with a made-up rate of 1.08)Another example capitalizes every word:
"the quick fox".replace(/\b\w/g, (c) => c.toUpperCase());
// "The Quick Fox"In Python, re.sub accepts a function that receives a match object: re.sub(r"\d+", lambda m: str(int(m.group()) * 2), "3 apples") gives "6 apples."
Replacement functions keep regex focused on what it's good at, finding the pieces, while ordinary code handles the computation. Trying to do arithmetic or complex conditions inside a pattern is a sign you should switch to a function.
Step 8 of 13Note
Step 9 of 13Practice · What would you do?
What would you do?
A team must convert 2,000 dates in a document from MM/DD/YYYY to YYYY-MM-DD. A developer writes text.replace(/(\d{2})\/(\d{2})\/(\d{4})/, "$3-$1-$2"), runs it, and finds that only one date changed. What is wrong?
Step 10 of 13Practice · Code challenge
Write toUsDates(text) that converts every date written as YYYY-MM-DD in text into MM/DD/YYYY, leaving the rest of the text unchanged. Use named groups or numbered groups in a single replace call.
toUsDates("Due 2026-03-14.")toUsDates("2025-01-05 and 2025-12-31")toUsDates("nothing to change")
Step 11 of 13Tap to reveal
Replacement syntax across tools
JavaScript
$1,$2for numbered groups,$<name>for named groups,$&for the whole match and$$for a literal dollar sign. A function can replace the string for anything dynamic.Python
\1or\g<1>for numbered groups,\g<name>for named groups, written in a raw string.\g<0>inserts the whole match. A function receiving the match object handles logic.VS Code and most editors
$1and$2in the replace box, with the regex option turned on. Some editors also support\uor\lto change case.sed and many Unix tools
\1to\9in the replacement, and&for the whole match. Withsed -E, parentheses group without backslashes.
Step 12 of 13Note
Step 13 of 13Practice · Choose one
In Python, which replacement string swaps "Okafor, Ben" into "Ben Okafor" using re.sub(r"(\w+), (\w+)", ..., text)?
Lesson complete!