Regex for Text Cleaning
Use regular expressions to extract, validate, and normalize messy free-text fields.
In plain words
A regex is a mini language for describing the pattern of text you're looking for, so you can find or change it automatically.
Think of it like…
A stencil for spotting shapes in a pile of documents: you cut the stencil once (the pattern) and run it over every page. A good stencil picks up exactly the shapes you want, and a sloppy one also picks up smudges.
Where you’ve seen it
A logistics team needs the PIN code from 800,000 free-text addresses such as "Flat 4B, Rose Apts, Baner, Pune 411045". df["address"].str.extract(r"\b([1-9]\d{5})\b") pulls six-digit PINs (not starting with 0) and word boundaries stop it matching part of a longer number. It finds one for 93 percent of rows; the rest are inspected and show missing PINs, not pattern failures.
Words you’ll hear
- Character classes
\ddigit,\wword character,\swhitespace,.any character,[a-z]a set.- Quantifiers
*zero or more,+one or more,?optional,{n,m}between n and m.- Groups and captures
- Parentheses capture the part you want;
(?:...)groups without capturing. - Anchors / boundaries
^start,$end,\bword boundary.
Visual diagram
Theory & deep dive
Building blocks and pandas methods
Combine literal characters with classes, quantifiers, groups and anchors: \d{10} is ten digits, [A-Z]{2}\d{4} is two capitals and four digits, (?i)error ignores case, a|b means a or b. Word boundaries \b stop a pattern matching inside a longer token. Always write patterns as raw strings (r"\d+") so Python doesn't treat backslashes as escapes.
In pandas: s.str.contains(pat, regex=True, na=False) returns a boolean mask; s.str.extract(r"(\d+)") returns the first capture group (one column per group); s.str.extractall(...) returns every match; s.str.replace(r"\s+", " ", regex=True) collapses whitespace; s.str.findall(pat) lists all matches. In the re module, re.search, re.findall, re.sub and re.compile for reuse work the same way. Named groups ((?P<year>\d{4})) make extracted columns self-describing.
df["sku"].str.extract(r"^(?P<line>[A-Z]{2})-(?P<size>\d{2})-(?P<colour>[A-Z]{3})$") turns "TS-42-RED" into three columns named line, size and colour, and gives NaN for codes that don't fit, a built-in validation.
Pitfalls: greed, validation and performance
Greedy quantifiers (.*) match as much as possible: <b>.*</b> on "<b>a</b> and <b>b</b>" swallows everything between the first and last tag; use the lazy form .*? or a precise class ([^<]*). Over-permissive patterns accept junk (\d+ matches inside "INV20260145X"); anchors and boundaries make intent explicit. Don't use regex for nested or hierarchical formats such as HTML, JSON or full email validity per the RFC, where a parser or a library like email-validator is correct.
Normalise before matching: lowercase, strip, and standardise Unicode (unicodedata.normalize("NFKC", text)) to handle odd spaces and full-width digits. For performance, compile reused patterns with re.compile, avoid nested quantifiers like (a+)+ that can backtrack catastrophically on crafted input, and prefer plain string methods when no pattern is needed (str.startswith is faster and clearer). Always report the match rate and inspect a sample of non-matches; a pattern is only as good as what you checked it against.
digits = df.phone.str.replace(r"\D", "", regex=True) removes everything except digits, then digits.str.extract(r"(\d{10})$") takes the last ten digits, so "+91 98765-43210" and "098765 43210" both become 9876543210.
How it works, step by step
Step 1 of 41. Collect real examples
Sample matching and non-matching values, including the ugly ones, before writing anything.
- Edge cases
- included
When to use it & trade-offs
What it is
A regular expression (regex) is a compact pattern for finding, validating, extracting and replacing text: \d{6} matches six digits, ^[\w.+-]+@[\w-]+\.[\w.]+$ roughly matches an email, and (\d+)-(\d+) captures two numbers. In Python use the re module; in pandas use .str.contains, .str.extract, .str.extractall and .str.replace(..., regex=True) to apply a pattern to a whole column. Regex is for structured-looking text such as codes, phone numbers and amounts, and it complements, not replaces, proper parsers.
Why it matters: Free-text columns (addresses, product titles, log lines, phone numbers) hold the facts you need in inconsistent formats. A few well-chosen patterns can pull out PIN codes, order IDs, prices or units from millions of rows in seconds, but careless patterns silently match the wrong thing or take forever on adversarial input. Interviewers often ask for a regex plus its edge cases.
When to reach for it
- Extracting codes, IDs and amounts from free text
- Validating formats such as PIN codes and SKUs
- Collapsing whitespace and removing noise characters
When to avoid or be careful
- Parsing HTML or JSON with regex
- Greedy
.*patterns over long text - Shipping a pattern without checking misses
Text extraction approaches
Strengths: Fast, compact, available everywhere.
Watch out: Hard to read and maintain; easy to over- or under-match.
Strengths: Clear and fast.
Watch out: Limited for variable formats.
Strengths: Correct on nested or ambiguous formats.
Watch out: Heavier dependencies; slower.
Interview signals & numbers to know
When this topic comes up
- “Extract the PIN code from the address”
- “Validate this format”
- “Why does my regex match too much?”
- Named groups
- Catastrophic backtracking
Benchmarks & rules of thumb
- \d{6}
- six digits (India PIN length)
- .*?
- lazy any-characters
- 93%
- match rate in the PIN example
Common mistakes & follow-ups
Common interview mistakes
- Writing "\d+" without a raw string or boundaries and matching digits inside longer IDs.
- Using a greedy
.*and capturing far more text than intended. - Reporting extracted values without checking how many rows didn't match.
Likely interviewer follow-ups
- How would you extract the PIN code from free-text addresses?
- What's the difference between greedy and lazy quantifiers?
- When is regex the wrong tool?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Regex for Text Cleaning with data science interview Q&A and hands-on practice.