Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 16/ 160
01. Python & Data Wrangling

Regex for Text Cleaning

Use regular expressions to extract, validate, and normalize messy free-text fields.

IntermediatePatterns · Groups3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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
\d digit, \w word character, \s whitespace, . 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, \b word boundary.

Visual diagram

Loading interactive 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.

Splitting a code into parts

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.

Key takeaway: Raw strings, anchors, capture groups and the .str methods cover most cleaning.

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.

Phone numbers: normalise, then match

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.

Key takeaway: Use lazy or specific patterns, normalise first, don't parse nested formats with regex, and audit misses.

How it works, step by step

Step 1 of 4
Discovery

1. Collect real examples

Sample matching and non-matching values, including the ugly ones, before writing anything.

20 addresses with and without PINs
Key numbers at this step
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

Regex
Best for: Codes, numbers, dates and phone numbers with predictable shape

Strengths: Fast, compact, available everywhere.

Watch out: Hard to read and maintain; easy to over- or under-match.

String methods (split, startswith, strip)
Best for: Simple, fixed-structure text

Strengths: Clear and fast.

Watch out: Limited for variable formats.

Parsers / NLP / libraries
Best for: HTML, JSON, addresses, names, emails

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?
Interview tip: Show the pattern, one tricky example it handles and one it deliberately rejects. That demonstrates you tested edge cases rather than guessed.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Regex for Text Cleaning with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Web Scraping & API Data Extraction
Next topic
Exploratory Data Analysis (EDA) Workflows