Skip to content

Lesson 8 of 9 · 23m

Substitution, Redaction, and Streaming Text Without Footguns

Use replacement functions safely, preserve auditability in redaction, handle overlapping and streamed data correctly, and avoid destructive one-shot regex edits.

Regex substitution feels safe because it is easy: replace secret, save file, move on. In production systems it is one of the fastest ways to corrupt data, redact the wrong thing, or create a false sense of compliance. Treat substitution as a transformation pipeline with invariants, not as a clever one-liner.

Replacement strings have their own escaping rules

In Python replacement strings, backslashes introduce group references:

import re

print(re.sub(r"(\w+)@example\.com", r"\1@redacted", "alice@example.com"))

If replacement content comes from a variable, a function is safer than a template string:

def mask(m):
    return m.group(1)[0] + "***@example.com"

re.sub(r"(\w+)@example\.com", mask, "alice@example.com")

A function receives the match object and returns exactly the replacement text: no accidental \1 processing and no ambiguity around backslashes.

Redaction needs a threat model

Decide whether you are hiding data from casual log readers, support staff, attackers with database access, or a compliance auditor. Keeping a domain may aid debugging but expose organizational information. Hashing with a stable salt aids correlation but creates a pseudonymous identifier. Irreversible masking is safer and less useful. Write the choice down.

Streaming requires overlap awareness

Regex over chunks breaks when a match spans a chunk boundary. Line-oriented processing is simplest. If you must process blocks, keep a trailing window or explicit record boundary:

tail = ""
for block in stream:
    data = tail + block
    boundary = data.rfind("\n")
    process(data[:boundary + 1])
    tail = data[boundary + 1:]

Multiline patterns require record-boundary logic; otherwise you will double-count, miss, or corrupt matches at seams.

Count substitutions and validate rewrites

re.subn returns the replacement count:

redacted, count = SECRET_RE.subn("[redacted]", payload)
if count != expected_count:
    raise RuntimeError("redaction count mismatch")

Regex rewrites can also destroy meaning in source code, configuration, and markup even when individual matches look correct. Use idempotence checks, parser validation, tests, and backups. For syntax-bearing files, prefer syntax-aware tools.

Field notes

  • Use replacement functions whenever replacement text is dynamic or contains backslashes.
  • Redaction is a policy decision: masking, hashing, truncation, and removal answer different questions.
  • Chunked processing needs explicit overlap or record-boundary handling.
  • Validate rewritten output with a parser or schema when the input format has one.
  • Count substitutions in compliance-sensitive pipelines and alert on impossible counts.

Was this lesson helpful?

Sign in to rate