Advanced String Processing: Regex and Text Cleanup
Real-world text arrives damaged. Phone numbers arrive with three different separators,
dates arrive in two orders, addresses arrive with trailing whitespace that no one can see,
and a column that was "never empty" turns out to contain the string null written by some
upstream tool. Splitting on commas and calling .strip() works until the first quoted
field containing a comma, and then the entire import silently shifts by one column.
Regular expressions are the tool that survives contact with this input β not because they
are powerful, but because they let you state the shape of valid data and let Python
enforce it.
This lesson builds from pattern anatomy to extraction to cleanup, then covers the performance and Unicode decisions that separate a pattern you can run over a million rows from one that makes the process hang.
The shape of a pattern worth writing
Every durable pattern starts by answering three questions: what must be at the start,
what must be at the end, and how much variability sits in the middle. Anchors (^ and
$) prevent a pattern from matching a fragment buried in longer text, quantifiers bound
the middle, and character classes state what is legal rather than enumerating what is
not. A pattern without anchors is the most common source of "it matched, but not the part
I meant".
import re
samples = [
" INV-2024-0087 ",
"invoice INV-2024-0087 paid",
"INV-2024-00871",
"INV-2024-0087",
]
loose = re.compile(r"INV-\d{4}-\d{4}")
tight = re.compile(r"^INV-\d{4}-\d{4}$")
for s in samples:
print(f"{s!r:40} loose={bool(loose.search(s))} tight={bool(tight.fullmatch(s.strip()))}")
Only the last two lines behave correctly under the anchored version, and the third sample
demonstrates why: without $, the pattern happily matches the first nine characters of a
ten-digit invoice number and your validation accepts an identifier that will never be
found later.
Greedy, lazy, and knowing which one you meant
Quantifiers are greedy by default β they consume as much as possible and then backtrack. That is usually what you want, but in delimited text it produces the classic bug where a pattern intended for one pair of quotes swallows everything between the first opening quote and the last closing one. A question mark after a quantifier makes it lazy, pulling the match back to the shortest string that still satisfies the pattern.
| Construct | Meaning | Typical use |
|---|---|---|
. | Any character except newline | Wildcard within a bounded span |
.* | Greedy: as much as possible | Pulling to end of line when that is correct |
.*? | Lazy: as little as possible | Stopping at the first delimiter |
\d / \D | Digit / non-digit | IDs, quantities, phone numbers |
\w / \W | Word character / non-word | Tokens; note it includes digits and underscore |
[A-Z]{2,5} | Class with bounded repeat | Country and state codes |
(?=...) | Positive lookahead | Requiring context without consuming it |
\b...\b | Word boundaries | Whole words only, avoiding substrings |
text = 'He said "stop" and then "go" loudly'
print(re.findall(r'"[^"]*"', text)) # ['"stop"', '"go"'] β lazy by construction
print(re.findall(r'".*"', text)) # ['"stop" and then "go"'] β greedy overreach
# whole-word match: 'cat' inside 'concatenate' must not count
print(re.findall(r"\bcat\b", "concatenate the cat")) # ['cat']
When a pattern must span to the end of a line but not beyond it, prefer a bounded class
such as [^"]* over .*?: the negated class states the boundary directly, reads faster,
and never wanders into catastrophic backtracking.
Named groups turn a match into a record
Positional groups age badly. Inserting one optional field near the front of a pattern
renumbers every group behind it, and the code reading match.group(3) fails in a way the
test suite may not catch if that branch was untested. Named groups survive edits,
self-document at the call site, and let you build a dictionary from the match directly.
LOG_LINE = re.compile(
r"^(?P<ts>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\s+"
r"(?P<level>[A-Z]+)\s+"
r"(?P<logger>[\w.]+)\s+-\s+"
r"(?P<msg>.*)$"
)
def parse(line: str) -> dict | None:
m = LOG_LINE.match(line.strip())
if not m:
return None
data = m.groupdict()
data["level"] = data["level"].lower()
return data
print(parse("2024-03-02T09:14:07 ERROR billing.retry - attempt 3 failed"))
# {'ts': '2024-03-02T09:14:07', 'level': 'error', 'logger': 'billing.retry',
# 'msg': 'attempt 3 failed'}
Alternation inside a named group and optional groups with defaults complete the pattern: at that point a regex is effectively a tiny parser with its own schema, which is exactly the right amount of machinery for one-line formats like logs, query strings, and configuration entries.
Cleanup that preserves meaning
Text cleanup is a sequence of decisions, not a single re.sub. Removing punctuation
outright destroys phone numbers and decimals; collapsing whitespace is nearly always safe;
lowercasing is safe for identifiers but destroys proper nouns. Write the pipeline so each
step is reviewable, and keep the raw string alongside the cleaned one until you trust the
routine.
def clean_field(raw: str) -> str:
text = raw.replace("\u00a0", " ") # non-breaking space from copy-paste
text = re.sub(r"\s+", " ", text) # collapse runs of any whitespace
text = text.strip()
text = re.sub(r"[ \t]+([,.;:])", r"\1", text) # remove space before punctuation
return text
def normalise_phone(raw: str) -> str | None:
digits = re.sub(r"\D", "", raw)
if len(digits) == 10:
return f"+1{digits}"
if len(digits) == 11 and digits.startswith("1"):
return f"+{digits}"
return None # signal: unparseable, do not guess
print(clean_field(" Order 12 , paid: yes\u00a0 "))
# Order 12, paid: yes
print(normalise_phone("(415) 555-0132")) # +14155550132
Notice that normalise_phone returns None rather than a half-cleaned string. Cleanup
routines that "do their best" on unparseable input are how corrupt values survive every
layer of a pipeline; failing to parse is information you should propagate.
Order matters as much as the substitutions themselves. Collapse whitespace before removing punctuation, or you will strand double spaces where a comma used to be. Normalise Unicode before case folding, or accented characters will survive into a slug you expected to be ASCII. When the pipeline grows past three or four steps, write it as a list of named functions and apply them in order β that makes the sequence reviewable in a pull request and lets you insert a step without rewriting the whole routine.
Compiled patterns and the cost of running them
re.sub and friends compile the pattern on every call. For a loop over a million rows
that is a million identical compilations, and the fix is one line: compile once at module
level and reuse the pattern object. Python caches a handful of recent patterns, but that
cache is keyed by the literal string β it helps repeated calls with the same expression
and does nothing for dynamically built ones.
DATE_VARIANTS = re.compile(
r"^(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})"
r"|(?P<d2>\d{1,2})/(?P<m2>\d{1,2})/(?P<y2>\d{4})$"
)
def normalise_date(value: str):
m = DATE_VARIANTS.match(value.strip())
if not m:
raise ValueError(f"unrecognised date: {value!r}")
if m.group("y"):
return f"{m.group('y')}-{m.group('m')}-{m.group('d')}"
return f"{m.group('y2')}-{int(m.group('m2')):02d}-{int(m.group('d2')):02d}"
Two further performance notes: bounded quantifiers ({2,5}) backtrack far less than
unbounded ones, and a pattern built from user input deserves a size limit β nested
unbounded groups can take exponential time on a hostile string, which is a denial-of-service
risk for any service that regex-validates a request body.
Unicode is not optional
Python 3 strings are Unicode, so \w matches letters from every script your data
contains, and lower() handles the characters where case folding is not a simple offset.
Three habits prevent the usual surprises. Use re.IGNORECASE rather than lowercasing both
sides by hand when you want case-insensitive comparison, prefer \w with an explicit
re.ASCII flag when you genuinely want the old byte-oriented behaviour, and never
measure "length" in characters for user-visible truncation without checking whether you
have split a grapheme cluster.
import unicodedata
def slugify(text: str, limit: int = 60) -> str:
decomposed = unicodedata.normalize("NFKD", text)
ascii_only = "".join(c for c in decomposed if not unicodedata.combining(c))
slug = re.sub(r"[^a-z0-9]+", "-", ascii_only.lower()).strip("-")
return slug[:limit].rstrip("-")
print(slugify("CafΓ© ΓberΓen β rΓ©sumΓ© 2024")) # cafe-ubersen-resume-2024
Normalization before stripping combining marks is what makes CafΓ© and Cafe produce the
same slug; skipping the normalization step leaves the accent intact and the link
duplicates the page it was supposed to consolidate.
Common Mistakes
Using search() with an unanchored pattern to validate input
Fix: Use fullmatch() with explicit anchors so partial matches cannot pass
Greedy patterns that swallow from the first delimiter to the last
Fix: Use a negated character class that stops at the next delimiter, or a lazy quantifier
Reading positional group numbers that shift when the pattern changes
Fix: Name every group and read them with groupdict()
Stripping all non-word characters during cleanup
Fix: Keep punctuation that carries meaning, and return None when a value cannot be parsed
Compiling the same pattern inside a hot loop
Fix: Compile once at module level and reuse the pattern object
Best Practices
- Write the test cases first β one accepted, one rejected, one adversarial β then the pattern
- Prefer bounded quantifiers and negated classes over unbounded wildcards
- Keep the raw value next to the cleaned value until the transformation has proven itself
- Limit the length of any string that will be matched with user-supplied patterns
- Extract one named group per field so the parsing code documents its own schema
Key Takeaways
- Anchors decide whether a pattern validates a string or merely finds a fragment
- Negated character classes express boundaries more safely than greedy wildcards
- Named groups keep extraction code readable and resistant to pattern edits
- Cleanup should signal failure rather than guess β return None on unparseable input
- Compile patterns once and bound their quantifiers before running them at scale