Skip to content

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 FATAL

The 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/28

Lookup 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: failover

Case-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/2025

expand 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.log

In 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

  • replaceAll throws TypeError when its regex lacks g — same rule as matchAll.
  • 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.sub takes count=n for "first n matches only"; re.subn returns (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.