Lesson 8 of 13 · 18m
Replace with a Function: Computed Replacements
When the replacement depends on the match — String.replace callbacks, re.sub callables, lookup tables, and the cliff edge where a callback becomes a tokenizer.
A static replacement string tops out the moment the replacement depends on what matched. "Uppercase every log level," "mask all but the last four digits," "rewrite every old.cdn.example host to cdn.example.com" — none of these are substitution problems. They're small computations, and every mainstream engine lets you run one per match.
The callback signature
const levels = "info connected warn retrying error fatal";
console.log(levels.replace(/\b(info|warn|error|fatal)\b/g, m => m.toUpperCase()));
// INFO connected WARN retrying ERROR FATALThe function receives (match, group1, group2, ..., offset, string) — plus a trailing groups object when the pattern uses named groups. The offset argument is the one people forget: it tells you where the match sat in the original string, which matters when the right replacement depends on position (first match gets a header, later ones don't). Python hands you the Match object instead:
import re
def mask(m):
digits = m.group(0)
return "*" * (len(digits) - 4) + digits[-4:]
print(re.sub(r"\b\d{12,19}\b", mask, "card 4242424242424242 exp 12/28"))
# card ************4242 exp 12/28Lookup tables are the killer use
const HOSTS = { "old.sudosecurity.org": "sudosecurity.org", "dev.sudosecurity.org": "sudosecurity.org" };
const rewrite = s => s.replace(/\b(?:old|dev)\.sudosecurity\.org\b/g, m => HOSTS[m] ?? m);A table plus a callback renames across ten thousand lines without writing ten thousand lines. The same shape scrubs secrets: (?<=token=)\S+ → m => mask(m). Keep reading, though — there is a limit.
A worked pass: normalize log levels
import re
CANON = {"warn": "WARN", "warning": "WARN", "err": "ERROR", "error": "ERROR", "crit": "FATAL"}
fix = re.compile(r"\b(warn|warning|err|error|crit)\b", re.I)
line = "2025-03-14 err: disk full; warning: retries exhausted; crit: failover"
print(fix.sub(lambda m: CANON[m.group(1).lower()], line))
# 2025-03-14 ERROR: disk full; WARN: retries exhausted; FATAL: failoverCase-insensitive match, canonical-case output, one line of transformation. This is the shape of every real scrubber and normalizer you'll write.
Python's match.expand
m = re.search(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})", "2025-03-14")
print(m.expand(r"\g<d>/\g<m>/\g<y>")) # 14/03/2025expand runs the replacement-template rules (\g<name>, \1) against one match — useful when you already hold a Match and don't need a full sub.
awk doesn't have callbacks — and doesn't need them
gsub only takes a literal replacement, but awk's whole model is per-field computation, so you rarely miss callbacks:
awk '{ $3 = toupper($3); print }' access.logIn awk you assign the field. That is the callback.
sed has no callback at all — the s///e flag (GNU only) executes the replacement as a shell command, which is exactly as dangerous as it sounds on untrusted input. On a pipeline that processes real data, reach for awk or a ten-line script before sed e.
The cliff edge
When the callback starts growing branches — "if inside a code block, don't touch; if in a link, only the host" — you've written a tokenizer with extra steps. A Markdown transformer that skips fenced code blocks is a parser's job; this is why every "regex to strip HTML comments" eventually eats a > inside an attribute. Callbacks are for mechanical transforms, not grammar awareness.
Field notes
replaceAllthrows TypeError when its regex lacksg— same rule asmatchAll.- In JS replacement strings,
$&,$',$`, and$$are magic. With a callback, the return value is used as data and none of that applies — one more reason callbacks beat template strings for untrusted text. re.subtakescount=nfor "first n matches only";re.subnreturns(new_string, n_substitutions)so you can assert the scrub actually fired.- Callbacks run per match, sequentially. On a hot path over millions of matches the call overhead is real — but the fix is a tighter pattern that matches fewer times, not a cleverer callback.
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.