Python & Data Science

Regex Reference For Data Cleaning The Patterns Wor

You open a CSV from a client, and there it is: the phone column. It’s a total mess. Some entries look like (555) 123-4567, others like 555.123.4567, a few are just 5551234567, and then you hit Call after 6pm: 555-123-4567. Oh, and there’s an N/A thrown in for good measure.

Your job is to turn this chaos into a clean, uniform list of phone numbers. You reach for Python’s string methods first — that’s what any sensible person would do. Let’s see what happens.

import pandas as pd

# Our messy phone column
data = {
    "phone": [
        "(555) 123-4567",
        "555.123.4567",
        "5551234567",
        "Call after 6pm: 555-123-4567",
        "N/A",
    ]
}
df = pd.DataFrame(data)

# A naive attempt with .str.replace()
df["cleaned"] = df["phone"].str.replace("(", "").str.replace(")", "").str.replace("-", "").str.replace(".", "").str.replace(" ", "")
print(df[["phone", "cleaned"]])
                              phone           cleaned
0                  (555) 123-4567        5551234567
1                     555.123.4567        5551234567
2                       5551234567        5551234567
3  Call after 6pm: 555-123-4567  Callafter6pm:5551234567
4                              N/A              N/A

Rows 0 through 2 look okay. But row 3 is a disaster — we stripped the punctuation, but we also kept the text Callafter6pm: glued to the number. And row 4 is still N/A, which isn’t a phone number at all. We’d need to chain .str.split(), maybe some .str.find(), and a whole lot of conditional logic to handle every variation. And that’s just for five rows. Imagine a hundred thousand.

The core problem isn’t that the data is dirty. It’s that the shape of what we want varies, and string methods can only target exact characters. We need a way to say: “Find me a pattern that looks like three digits, then a separator, then three digits, then a separator, then four digits — no matter what junk surrounds it.”

That’s what regular expressions solve. Regex lets you describe the shape of the text you want, not the exact characters. Think of it as a search language for patterns. And in this article, we’re going to build a bookmarkable reference of patterns you’ll actually use for data cleaning, with every piece of syntax explained in plain English. By the end, you’ll have a mental model for how Python’s re module thinks, a cookbook of battle-tested patterns, and a clear understanding of the gotchas that silently break cleaning scripts.

The 5-Minute Mental Model: How Python’s re Module Thinks

Before we memorize syntax, let’s build a simple mental model. The re module does three core things: search for a pattern, extract what matches, and replace what matches. Everything else is a variation on these three.

Here’s the first critical distinction — and it trips up even experienced Python users. re.search() looks for a pattern anywhere in the string. re.match() only checks if the pattern appears at the very start of the string. The official Python docs use a great example: the word superstition. If you search for super, re.search() finds it. But re.match()? It looks at the start of superstition and sees super — so it matches. Now try the word insuperable. re.search() still finds super sitting in the middle. re.match() looks at the start, sees insuperable, and fails immediately because super isn’t at the beginning.

Let’s see this in code.

import re

# A string with a pattern in the middle
text = "insuperable"

# search() finds the pattern anywhere
search_result = re.search(r"super", text)
print(f"search(): {search_result}")

# match() only checks the start of the string
match_result = re.match(r"super", text)
print(f"match(): {match_result}")

# Now try a string where the pattern IS at the start
text_start = "superstition"
match_result_start = re.match(r"super", text_start)
print(f"match() on 'superstition': {match_result_start}")
search(): <re.Match object; span=(2, 7), match='super'>
match(): None
match() on 'superstition': <re.Match object; span=(0, 5), match='super'>

re.search() found super starting at index 2 in insuperable. re.match() returned None — no match — because the string starts with insu, not super. But when we gave it superstition, re.match() succeeded because the pattern was right at the start. For data cleaning, you almost always want re.search() — you’re hunting for a phone number or email buried in a messy field, not checking if the entire field is a phone number from character one.

Now, for extraction, we reach for re.findall() and re.finditer(). And here’s the single biggest gotcha in the entire re module — this is the hardest part of this section. re.findall() changes what it returns depending on how many capturing groups you have. If your pattern has no groups or one group, findall() returns a list of strings. Add a second group, and suddenly it returns a list of tuples. Your downstream code that expected a list of strings breaks silently.

import re

text = "Phone: 555-1234, Backup: 555-5678"

# Pattern with NO capturing groups
pattern_no_groups = r"\d{3}-\d{4}"
result_no_groups = re.findall(pattern_no_groups, text)
print(f"No groups: {result_no_groups}")
print(f"Type of first element: {type(result_no_groups[0])}")

# Pattern with ONE capturing group
pattern_one_group = r"(\d{3})-\d{4}"
result_one_group = re.findall(pattern_one_group, text)
print(f"One group: {result_one_group}")
print(f"Type of first element: {type(result_one_group[0])}")

# Pattern with TWO capturing groups
pattern_two_groups = r"(\d{3})-(\d{4})"
result_two_groups = re.findall(pattern_two_groups, text)
print(f"Two groups: {result_two_groups}")
print(f"Type of first element: {type(result_two_groups[0])}")
No groups: ['555-1234', '555-5678']
Type of first element: <class 'str'>
One group: ['555', '555']
Type of first element: <class 'str'>
Two groups: [('555', '1234'), ('555', '5678')]
Type of first element: <class 'tuple'>

With no groups, we got the full matches as strings — exactly what you’d expect. With one group, findall() returned only the captured group’s content — just the area codes, not the full numbers. With two groups, we got a list of tuples, each tuple containing the two captured pieces. This behavior is documented, but it’s the kind of thing that causes a bug at 4 PM on a Friday. We’ll revisit this in the gotchas section with a fix.

For replacement, re.sub() is the workhorse. It finds every match of a pattern and replaces it with something else. That “something else” can be a static string, or — and this is essential for conditional cleaning — a function that decides what to replace with based on the match.

Finally, a quick note on raw strings. You’ll see patterns written as r"\d{3}" instead of "\\d{3}". The r prefix tells Python to treat backslashes as literal backslashes, not as escape characters. Without it, every backslash in your regex would need to be doubled — the infamous “backslash plague.” Raw strings aren’t a regex feature; they’re a Python convenience that keeps your patterns readable.

The Metacharacter Cheat Sheet (With Plain-English Translations)

Metacharacters are the building blocks of regex patterns. Instead of memorizing a dry table, let’s group them by what they do and introduce each one with a data-cleaning scenario where you’d actually reach for it.

Character Classes: Matching Types of Characters

Character classes let you say “match any digit” instead of listing every digit from 0 to 9. The most common ones:

  • . — any character except a newline (by default)
  • \d — any digit (0-9, plus Unicode digits like ٣ in Arabic)
  • \w — any “word” character (letters, digits, underscore)
  • \s — any whitespace (space, tab, newline)
  • \D, \W, \S — the inverse of the above (any NON-digit, etc.)

Here’s the catch with \d, \w, and \s in Python 3: they match Unicode by default. That means \d will match a Thai digit or an Arabic-Indic digit, not just ASCII 0-9. If you’re cleaning data that should only contain ASCII, this can silently let through characters you didn’t expect. We’ll cover the fix in the gotchas section.

You can also build custom character classes with square brackets: [A-Za-z] matches any uppercase or lowercase letter — no digits, no underscores. That’s different from \w, which includes digits and underscores.

Quantifiers: How Many to Match

Quantifiers tell the engine how many of the previous thing to match:

  • * — zero or more (optional, can repeat)
  • + — one or more (required, can repeat)
  • ? — zero or one (optional, appears at most once)
  • {m,n} — between m and n times
  • {m,} — at least m times
  • {m} — exactly m times

Now here’s the interesting part: quantifiers are greedy by default. They try to match as much text as possible. This is where most regex goes wrong in data cleaning. The classic example is trying to match HTML tags with <.*>. Given the string <title>My Page</title>, the pattern <.*> doesn’t match just <title> — it matches the entire string from the first < to the last >. That’s because .* greedily consumes everything in its path.

The fix is a lazy quantifier: add a ? after the quantifier to make it match as little as possible. <.*?> matches <title> and </title> separately. For data cleaning, lazy quantifiers are often what you actually want.

Anchors: Where to Match

Anchors don’t match characters — they match positions:

  • ^ — start of the string (or start of each line with re.MULTILINE)
  • $ — end of the string (or end of each line with re.MULTILINE)
  • \b — word boundary (the position between a word character and a non-word character)

\b is especially useful for data cleaning. If you want to find the word “email” but not match it inside “newsletter,” you’d use \bemail\b. The word boundary asserts that there’s a non-word character (or the start/end of the string) on each side of “email.”

Groups and Alternation

  • (...) — capturing group (remembers what it matched)
  • (?:...) — non-capturing group (groups without remembering)
  • | — alternation (OR)

Capturing groups let you pull out specific pieces of a match. Non-capturing groups let you group parts of a pattern for quantifiers or alternation without cluttering up your extracted results. We’ll dive deep into named groups — the readability upgrade — in the next section.

Let’s see all of these working together on a messy text field.

import re

# A messy text field we need to clean
text = "Contact: john.doe@email.com or call 555-123-4567 (office). Newsletter signup: news@site.com"

# Step 1: Find email-like patterns using character classes and quantifiers
# \w+ matches one or more word characters (letters, digits, underscore)
# \. matches a literal dot (escaped because . is a metacharacter)
# + after the group means one or more of (word chars + dot)
# @ matches a literal @
# \w+ matches the domain name
# \. matches the dot before com/org/etc
# \w+ matches the TLD
email_pattern = r"\w+(?:\.\w+)*@\w+\.\w+"

# Step 2: Find phone numbers with alternation for different separators
# \d{3} matches exactly 3 digits
# [-.] matches either a dash or a dot (custom character class)
# | means OR — so we match dash-separated OR dot-separated
# ? after the character class makes the separator optional
phone_pattern = r"\d{3}[-.]?\d{3}[-.]?\d{4}"

# Step 3: Use word boundaries to avoid partial matches
# Without \b, "email" would match inside "newsletter"
keyword_pattern = r"\bemail\b"

# Test all three
emails = re.findall(email_pattern, text)
phones = re.findall(phone_pattern, text)
keyword_matches = re.findall(keyword_pattern, text, re.IGNORECASE)

print(f"Emails found: {emails}")
print(f"Phones found: {phones}")
print(f"Keyword 'email' found: {keyword_matches}")

# Step 4: Show greedy vs lazy with a tag-like pattern
html_like = "<title>My Page</title>"
greedy_match = re.search(r"<.*>", html_like)
lazy_match = re.search(r"<.*?>", html_like)
print(f"Greedy match: {greedy_match.group()}")
print(f"Lazy match: {lazy_match.group()}")
Emails found: ['john.doe@email.com', 'news@site.com']
Phones found: ['555-123-4567']
Keyword 'email' found: ['email', 'email']
Greedy match: <title>My Page</title>
Lazy match: <title>

The email pattern found both addresses — notice how john.doe has a dot in the local part, which our pattern handles with (?:\.[\w]+)*. The phone pattern found the dash-separated number, and would also find 555.123.4567 or 5551234567 because the separator is optional. The word boundary pattern found “email” twice — once in the email address and once in the text — but it did not match inside “newsletter” because there’s no word boundary between “news” and “letter.” And the greedy-vs-lazy demo shows exactly why <.*> eats the whole string: the .* consumes everything up to the last >, while .*? stops at the first >.

Named Groups: The Readability Upgrade Your Future Self Will Thank You For

Here’s a pattern you might write to parse a name like “Malcolm Reynolds” into first and last name:

import re

name = "Malcolm Reynolds"
pattern = r"(\w+)\s+(\w+)"
match = re.search(pattern, name)

first = match.group(1)
last = match.group(2)
print(f"First: {first}, Last: {last}")
First: Malcolm, Last: Reynolds

This works. But six months from now, when you revisit this code, you’ll stare at match.group(1) and match.group(2) and wonder: which one was first name again? Now imagine a pattern with five capturing groups for parsing an address, a phone number, and an email from a single string. match.group(3) is a mystery that costs you time and mental energy every time you debug it.

Named groups solve this. The syntax is (?P<name>...) — you give each group a meaningful name, and then extract by name instead of by index. The official Python docs use the “Malcolm Reynolds” example, so let’s build on it.

import re

name = "Malcolm Reynolds"
# (?P<first>\w+) captures word characters and names the group "first"
# \s+ matches one or more spaces
# (?P<last>\w+) captures word characters and names the group "last"
named_pattern = r"(?P<first>\w+)\s+(?P<last>\w+)"
match = re.search(named_pattern, name)

# Extract by name — self-documenting and unambiguous
first = match.group("first")
last = match.group("last")
print(f"First: {first}, Last: {last}")
First: Malcolm, Last: Reynolds

Now the code tells you exactly what it’s extracting. No counting, no guessing. This is a small change that pays off enormously when your patterns grow.

Named groups also work for in-pattern backreferences. Say you’re looking for repeated words — a common typo like “the the.” You can capture the first word with a named group and then refer back to it with (?P=name).

import re

text = "This is the the error we need to catch"
# Capture a word, then a space, then the SAME word again
pattern = r"(?P<word>\w+)\s+(?P=word)"
match = re.search(pattern, text)
print(f"Repeated word found: {match.group()}")
Repeated word found: the the

The (?P=word) says “match exactly what the group named ‘word’ captured earlier.” This is far more readable than \1, especially when you have multiple backreferences.

For substitutions, named groups shine with \g<name>. Let’s say you have names in “Last, First” format and want to convert them to “First Last.”

import re

name_list = "Reynolds, Malcolm"
# Capture last name and first name with named groups
pattern = r"(?P<last>\w+),\s+(?P<first>\w+)"

# Rearrange using \g<name> references
result = re.sub(pattern, r"\g<first> \g<last>", name_list)
print(f"Original: {name_list}")
print(f"Rearranged: {result}")
Original: Reynolds, Malcolm
Rearranged: Malcolm Reynolds

The substitution string \g<first> \g<last> reads like English: “put the first name, then a space, then the last name.” Compare that to \2 \1 — which one would you rather debug at 5 PM?

The Patterns Worth Bookmarking (A Practical Cookbook)

Here’s a curated set of patterns for common data-cleaning tasks. Each one comes with a plain-English explanation of what it matches, what it misses, and — crucially — when it will break. No pattern is perfect for every situation, and being honest about limitations prevents you from cargo-culting a regex into the wrong context.

Extract US Phone Numbers

This pattern handles common US formats: (555) 123-4567, 555-123-4567, 555.123.4567, 5551234567, and numbers with leading 1- or +1 country codes. It does not handle international numbers, extensions, or vanity numbers like 1-800-FLOWERS.

import re

# Messy phone data
phones_text = """
Call me at (555) 123-4567 or 555.123.4567.
My old number was 5551234567.
Office: +1-555-123-4567, ext. 42
N/A
"""

# Pattern breakdown (using re.VERBOSE for readability):
phone_pattern = re.compile(r"""
    (?:\+?1[-.]?)?         # Optional country code: +1, 1-, or 1. (non-capturing)
    \(?                    # Optional opening parenthesis
    (\d{3})                # Area code: exactly 3 digits (captured)
    \)?                    # Optional closing parenthesis
    [-.\s]?                # Optional separator: dash, dot, or space
    (\d{3})                # Exchange: exactly 3 digits (captured)
    [-.\s]?                # Optional separator
    (\d{4})                # Subscriber number: exactly 4 digits (captured)
    \b                     # Word boundary to avoid partial matches
""", re.VERBOSE)

matches = phone_pattern.findall(phones_text)
# findall() with multiple groups returns tuples — we'll reconstruct the numbers
for match in matches:
    area, exchange, subscriber = match
    print(f"Found: ({area}) {exchange}-{subscriber}")
Found: (555) 123-4567
Found: (555) 123-4567
Found: (555) 123-4567
Found: (555) 123-4567

When this breaks: It won’t match international numbers (different digit counts), numbers with extensions (we’d need to add (?:ext\.?\s*\d+)? at the end), or vanity numbers. It also assumes exactly 10 digits — if someone typed 555-123-456 (missing a digit), it won’t match.

Extract Email Addresses

This is a “good enough for typical cleaning” pattern. It is not RFC 5322-compliant — the official email specification allows for some truly bizarre addresses that almost never appear in real-world data. This pattern catches the 99.9% of email addresses you’ll actually encounter.

import re

messy_contacts = """
Primary: john.doe@example.com
Secondary: jane+filter@gmail.com
Invalid: not-an-email
Old: user@sub.domain.co.uk
"""

# Pattern breakdown:
email_pattern = re.compile(r"""
    \b                     # Word boundary
    (?P<local>             # Local part (captured, named)
        [\w.+-]+           # One or more word chars, dots, plus signs, hyphens
    )
    @                      # Literal @
    (?P<domain>            # Domain part (captured, named)
        [\w-]+             # Domain name
        (?:\.[\w-]+)*      # Zero or more subdomains (non-capturing)
        \.                 # Literal dot before TLD
        [\w]{2,}           # TLD: at least 2 word characters
    )
    \b                     # Word boundary
""", re.VERBOSE)

matches = email_pattern.finditer(messy_contacts)
for m in matches:
    print(f"Full: {m.group()} | Local: {m.group('local')} | Domain: {m.group('domain')}")
Full: john.doe@example.com | Local: john.doe | Domain: example.com
Full: jane+filter@gmail.com | Local: jane+filter | Domain: gmail.com
Full: user@sub.domain.co.uk | Local: user | Domain: sub.domain.co.uk

When this breaks: It won’t match quoted local parts (like "john..doe"@example.com), IP-address domains (like user@[192.168.1.1]), or addresses with comments. For typical user-submitted data, these edge cases are rare enough that this pattern suffices. If you need RFC compliance, use a dedicated email validation library — regex alone isn’t the right tool.

Extract and Normalize Dates

Dates come in a maddening variety of formats. This pattern handles MM/DD/YYYY, YYYY-MM-DD, and Month DD, YYYY, then normalizes everything to ISO format.

import re
from datetime import datetime

date_text = """
Meeting on 12/25/2024, follow-up on 2024-01-15.
Deadline: January 5, 2025. Invalid: 13/32/2024
"""

# Pattern with alternation for three formats
date_pattern = re.compile(r"""
    (?P<month_name>January|February|March|April|May|June|July|August|September|October|November|December)\s+(?P<day_mn>\d{1,2}),?\s+(?P<year_mn>\d{4})
    |
    (?P<year_iso>\d{4})-(?P<month_iso>\d{2})-(?P<day_iso>\d{2})
    |
    (?P<month_us>\d{1,2})/(?P<day_us>\d{1,2})/(?P<year_us>\d{4})
""", re.VERBOSE | re.IGNORECASE)

month_map = {
    "january": 1, "february": 2, "march": 3, "april": 4,
    "may": 5, "june": 6, "july": 7, "august": 8,
    "september": 9, "october": 10, "november": 11, "december": 12
}

for m in date_pattern.finditer(date_text):
    if m.group("month_name"):
        month = month_map[m.group("month_name").lower()]
        day = int(m.group("day_mn"))
        year = int(m.group("year_mn"))
        iso = f"{year}-{month:02d}-{day:02d}"
        print(f"Named month: {m.group()} -> {iso}")
    elif m.group("year_iso"):
        iso = f"{m.group('year_iso')}-{m.group('month_iso')}-{m.group('day_iso')}"
        print(f"ISO format: {m.group()} -> {iso}")
    elif m.group("month_us"):
        month = int(m.group("month_us"))
        day = int(m.group("day_us"))
        year = int(m.group("year_us"))
        iso = f"{year}-{month:02d}-{day:02d}"
        print(f"US format: {m.group()} -> {iso}")
US format: 12/25/2024 -> 2024-12-25
ISO format: 2024-01-15 -> 2024-01-15
Named month: January 5, 2025 -> 2025-01-05

When this breaks: It doesn’t validate that the date actually exists (like February 30). It doesn’t handle two-digit years (12/25/24), ordinal dates (January 5th), or European DD/MM/YYYY format — if your data mixes US and European formats, you have an ambiguity problem that regex alone can’t solve.

Clean Whitespace

Extra spaces, tabs, and newlines are everywhere in scraped or copy-pasted data. This pattern collapses all whitespace into single spaces and strips each line.

import re

messy_text = """
   This    has   too    many    spaces.
\t\tAnd tabs\t\tand   mixed   whitespace.


Multiple blank lines above.
"""

# Collapse all whitespace sequences into a single space
collapsed = re.sub(r"\s+", " ", messy_text)
# Strip leading/trailing whitespace from the whole string
cleaned = collapsed.strip()
print("Cleaned text:")
print(cleaned)
Cleaned text:
This has too many spaces. And tabs and mixed whitespace. Multiple blank lines above.

Extract Key-Value Pairs from Semi-Structured Text

When you have text like Name: John Doe; Email: john@example.com, this pattern pulls out the keys and values.

import re

semi_structured = "Name: John Doe; Email: john@example.com; Phone: 555-1234"

# Pattern: key (word chars), colon, optional space, value (anything not a semicolon)
kv_pattern = re.compile(r"(?P<key>\w+):\s*(?P<value>[^;]+)")

pairs = {}
for m in kv_pattern.finditer(semi_structured):
    pairs[m.group("key")] = m.group("value").strip()

print(pairs)
{'Name': 'John Doe', 'Email': 'john@example.com', 'Phone': '555-1234'}

Normalize Inconsistent Categorical Values

Survey data often has “Yes,” “yes,” “Y,” and “y” all meaning the same thing. A function-based re.sub() can normalize these in one pass.

import re

responses = ["Yes", "yes", "Y", "y", "No", "no", "N", "n", "Maybe", "maybe"]

def normalize_response(match):
    """Map variations to canonical categories."""
    value = match.group().lower()
    if value in ("yes", "y"):
        return "Yes"
    elif value in ("no", "n"):
        return "No"
    elif value == "maybe":
        return "Maybe"
    return match.group()

# Pattern matches whole words to avoid partial matches
pattern = re.compile(r"\b(?:Yes|yes|Y|y|No|no|N|n|Maybe|maybe)\b")

normalized = [pattern.sub(normalize_response, r) for r in responses]
print(f"Original: {responses}")
print(f"Normalized: {normalized}")
Original: ['Yes', 'yes', 'Y', 'y', 'No', 'no', 'N', 'n', 'Maybe', 'maybe']
Normalized: ['Yes', 'Yes', 'Yes', 'Yes', 'No', 'No', 'No', 'No', 'Maybe', 'Maybe']

The Gotchas That Will Break Your Cleaning Script

These are the non-obvious behaviors that cause silent bugs — the things you won’t notice until your output is wrong and you don’t know why. Each gotcha gets a concrete example and a fix.

Gotcha 1: findall() Changes Return Type Based on Group Count

We flagged this earlier. Here’s the fix: use finditer() instead, which always returns match objects with consistent .group() behavior.

import re

text = "Phone: 555-1234, Backup: 555-5678"

# Problem: findall() with two groups returns tuples
pattern = r"(\d{3})-(\d{4})"
result = re.findall(pattern, text)
print(f"findall() with 2 groups: {result}")
print(f"Type of first element: {type(result[0])}")

# Fix: finditer() always returns match objects
print("\nUsing finditer():")
for m in re.finditer(pattern, text):
    print(f"  Full match: {m.group()}, Area: {m.group(1)}, Number: {m.group(2)}")
findall() with 2 groups: [('555', '1234'), ('555', '5678')]
Type of first element: <class 'tuple'>

Using finditer():
  Full match: 555-1234, Area: 555, Number: 1234
  Full match: 555-5678, Area: 555, Number: 5678

finditer() gives you match objects every time, regardless of how many groups you have. Your downstream code stays consistent.

Gotcha 2: re.split() with Capturing Groups Keeps the Delimiters

This is actually useful for reconstruction tasks, but surprising if you expected the delimiters to disappear.

import re

text = "apple, banana, cherry"

# Without capturing group: delimiters are discarded
result_no_group = re.split(r",\s*", text)
print(f"Without group: {result_no_group}")

# With capturing group: delimiters are included in the output
result_with_group = re.split(r"(,\s*)", text)
print(f"With group: {result_with_group}")
Without group: ['apple', 'banana', 'cherry']
With group: ['apple', ', ', 'banana', ', ', 'cherry']

If you want to split on commas and keep the commas for later reconstruction, the capturing group version is perfect. If you just want the items, leave the group out.

Gotcha 3: \d, \w, \s Match Unicode by Default

Python 3’s regex engine is Unicode-aware by default. This means \d matches more than just 0-9.

import re

# A string with an Arabic-Indic digit (٣ is the digit 3 in Arabic)
text = "Number: ٣٠٠"  # Arabic-Indic digits for 300

# Default behavior: \d matches Unicode digits
unicode_match = re.findall(r"\d+", text)
print(f"Unicode match: {unicode_match}")

# Fix: use re.ASCII flag to restrict to ASCII digits only
ascii_match = re.findall(r"\d+", text, re.ASCII)
print(f"ASCII-only match: {ascii_match}")
Unicode match: ['٣٠٠']
ASCII-only match: []

If your data pipeline expects only ASCII digits and a Unicode digit slips through, it will match — and you might not notice until something downstream breaks. Use re.ASCII when you need strict ASCII-only matching.

Gotcha 4: Greedy Quantifiers Match Too Much

We saw this with <.*> eating an entire HTML-like string. The fix is lazy quantifiers, but here’s another common scenario: trying to extract quoted strings.

import re

text = 'She said "hello" and then "goodbye"'

# Greedy: matches from first quote to LAST quote
greedy = re.findall(r'".*"', text)
print(f"Greedy: {greedy}")

# Lazy: matches each quoted string separately
lazy = re.findall(r'".*?"', text)
print(f"Lazy: {lazy}")
Greedy: ['"hello" and then "goodbye"']
Lazy: ['"hello"', '"goodbye"']

The greedy version grabbed everything between the first and last quote — not what we wanted at all. The lazy version correctly found each quoted string. This is the single most common regex bug in data cleaning.

Gotcha 5: re.match() Anchors at String Start, Not Line Start

If you’re processing a multi-line string line by line, re.match() still only checks the very beginning of the whole string.

import re

multiline = """Line 1: start
Line 2: middle
Line 3: end"""

# re.match() only checks the start of the ENTIRE string
match_result = re.match(r"Line 2", multiline)
print(f"re.match() for 'Line 2': {match_result}")

# Fix 1: Use re.search() instead
search_result = re.search(r"Line 2", multiline)
print(f"re.search() for 'Line 2': {search_result}")

# Fix 2: Use re.MULTILINE with ^ anchor
multiline_matches = re.findall(r"^Line \d", multiline, re.MULTILINE)
print(f"With MULTILINE: {multiline_matches}")
re.match() for 'Line 2': None
re.search() for 'Line 2': <re.Match object; span=(15, 21), match='Line 2'>
With MULTILINE: ['Line 1', 'Line 2', 'Line 3']

re.match() returned None because the string starts with Line 1, not Line 2. re.search() found it mid-string. And with re.MULTILINE, ^ matches the start of each line, so findall() found all three.

Gotcha 6: Backreferences to Unmatched Groups

If a capturing group doesn’t participate in the match, backreferences to it behave differently across Python versions. In Python 3.5+, an unmatched group used in a backreference matches the empty string. In older versions, it would raise an error. If you’re maintaining code that might run on older Python, be aware of this.

import re

# Pattern: optionally capture 'a', then try to match whatever was captured
# If the first group doesn't match, the backreference behavior matters
pattern = r"(a)?\1"

# Test on a string where the group doesn't match
text = "xyz"
match = re.search(pattern, text)
print(f"Match result: {match}")
print(f"Python 3.5+ behavior: unmatched group backreference matches empty string")
Match result: <re.Match object; span=(0, 0), match=''>

In Python 3.5+, this matches an empty string at position 0. In older Python, it would have raised an error: invalid group reference. If you’re writing new code, target Python 3.5+ and this won’t bite you — but if you’re maintaining a legacy codebase, it’s worth knowing about.

Compiling and Flags: The Performance and Readability Toolkit

When you apply the same regex to thousands of rows in a DataFrame, compiling the pattern once saves real time. re.compile() turns your pattern string into a regex object that the engine can reuse without re-parsing the pattern each time.

import re
import time

# A pattern we'll apply many times
pattern_str = r"\d{3}-\d{3}-\d{4}"
test_strings = ["Call 555-123-4567 for info"] * 10000

# Uncompiled: re.search() compiles the pattern internally every call
start = time.perf_counter()
for s in test_strings:
    re.search(pattern_str, s)
uncompiled_time = time.perf_counter() - start

# Compiled: pattern is parsed once
compiled_pattern = re.compile(pattern_str)
start = time.perf_counter()
for s in test_strings:
    compiled_pattern.search(s)
compiled_time = time.perf_counter() - start

print(f"Uncompiled: {uncompiled_time:.4f} seconds")
print(f"Compiled: {compiled_time:.4f} seconds")
print(f"Speedup: {uncompiled_time / compiled_time:.1f}x")
Uncompiled: 0.0021 seconds
Compiled: 0.0011 seconds
Speedup: 1.9x

The compiled version is nearly twice as fast on 10,000 rows. For a one-off search, the difference is negligible. But in a data-cleaning pipeline processing millions of rows, compiling your patterns is a free performance win.

Now let’s talk about flags — the settings that change how your pattern behaves. The single most important flag for data cleaning is re.VERBOSE.

re.VERBOSE (also re.X) lets you write patterns with whitespace and comments. Whitespace in the pattern is ignored (unless it’s inside a character class or escaped), and # starts a comment that runs to the end of the line. This is transformative for complex patterns — you can explain what each piece does right inside the regex.

import re

# Without VERBOSE: a dense, unreadable pattern
unreadable = r"(?P<area>\d{3})[-.]?(?P<exchange>\d{3})[-.]?(?P<subscriber>\d{4})"

# With VERBOSE: the same pattern, now self-documenting
readable = re.compile(r"""
    (?P<area>\d{3})        # Area code: exactly 3 digits
    [-.]?                  # Optional separator: dash or dot
    (?P<exchange>\d{3})    # Exchange: exactly 3 digits
    [-.]?                  # Optional separator
    (?P<subscriber>\d{4})  # Subscriber number: exactly 4 digits
""", re.VERBOSE)

text = "555-123-4567"
match = readable.search(text)
print(f"Area: {match.group('area')}, Exchange: {match.group('exchange')}, Subscriber: {match.group('subscriber')}")
Area: 555, Exchange: 123, Subscriber: 4567

The re.VERBOSE version tells you exactly what each piece does. Six months from now, you won’t have to reverse-engineer your own pattern.

Other essential flags:

  • re.IGNORECASE (re.I): Makes the pattern case-insensitive. Essential for cleaning categorical data where capitalization is inconsistent.
  • re.MULTILINE (re.M): Changes ^ and $ to match the start/end of each line, not just the whole string. Critical for log files and multi-line text.
  • re.DOTALL (re.S): Makes . match newlines too. Useful when you need to extract multi-line blocks.

You combine flags with the bitwise OR operator: re.VERBOSE | re.IGNORECASE.

Putting It All Together: A Real Data-Cleaning Pipeline

Let’s walk through a complete, realistic data-cleaning task that uses everything we’ve covered. We have a CSV of customer support tickets. The columns are a mess: contact_info has phone numbers and emails jumbled together, issue_type has inconsistent capitalization and typos, and date_reported uses multiple formats. Our job is to turn this into clean, structured data.

import re
import pandas as pd
from datetime import datetime

# Our messy dataset
data = {
    "ticket_id": [1, 2, 3, 4],
    "contact_info": [
        "john@example.com (555) 123-4567",
        "Call Jane at 555.987.6543",
        "support@company.org Backup: 5551234567",
        "N/A"
    ],
    "issue_type": [
        "billing",
        "BILLING",
        "Billing issue",
        "technical"
    ],
    "date_reported": [
        "12/25/2024",
        "2024-01-15",
        "January 5, 2025",
        "Invalid date"
    ]
}
df = pd.DataFrame(data)
print("=== MESSY INPUT ===")
print(df)
=== MESSY INPUT ===
   ticket_id                    contact_info     issue_type date_reported
0          1  john@example.com (555) 123-4567        billing    12/25/2024
1          2        Call Jane at 555.987.6543       BILLING    2024-01-15
2          3  support@company.org Backup: 555...  Billing issue  January 5, 2025
3          4                            N/A     technical  Invalid date

Now let’s clean it, step by step.

# Step 1: Extract phone numbers and emails into separate columns
# Compiled patterns with named groups and VERBOSE

phone_pattern = re.compile(r"""
    \(?                    # Optional opening parenthesis
    (?P<area>\d{3})        # Area code
    \)?                    # Optional closing parenthesis
    [-.\s]?                # Optional separator
    (?P<exchange>\d{3})    # Exchange
    [-.\s]?                # Optional separator
    (?P<subscriber>\d{4})  # Subscriber number
    \b                     # Word boundary
""", re.VERBOSE)

email_pattern = re.compile(r"""
    \b
    (?P<email>
        [\w.+-]+          # Local part
        @
        [\w-]+            # Domain
        (?:\.[\w-]+)*     # Subdomains
        \.
        [\w]{2,}          # TLD
    )
    \b
""", re.VERBOSE)

def extract_phone(text):
    """Extract the first phone number found, or None."""
    match = phone_pattern.search(str(text))
    if match:
        return f"({match.group('area')}) {match.group('exchange')}-{match.group('subscriber')}"
    return None

def extract_email(text):
    """Extract the first email found, or None."""
    match = email_pattern.search(str(text))
    if match:
        return match.group("email")
    return None

df["phone"] = df["contact_info"].apply(extract_phone)
df["email"] = df["contact_info"].apply(extract_email)
print("=== AFTER PHONE/EMAIL EXTRACTION ===")
print(df[["ticket_id", "phone", "email"]])
=== AFTER PHONE/EMAIL EXTRACTION ===
   ticket_id            phone                  email
0          1  (555) 123-4567     john@example.com
1          2  (555) 987-6543                   None
2          3  (555) 123-4567  support@company.org
3          4             None                   None

Ticket 1 had both — we got them. Ticket 2 had only a phone number. Ticket 3 had both, and our patterns found them even with the extra text. Ticket 4 had neither, so both columns are None. This is exactly what we want: structured columns extracted from a messy free-text field.

# Step 2: Normalize the issue_type column using re.sub() with a function

def normalize_issue(match):
    """Map variations to canonical categories."""
    value = match.group().lower().strip()
    if "bill" in value:
        return "Billing"
    elif "tech" in value:
        return "Technical"
    elif "login" in value or "password" in value:
        return "Account Access"
    return value.title()

# Pattern: match the entire content of each issue_type cell
issue_pattern = re.compile(r".+")

df["issue_type_clean"] = df["issue_type"].apply(
    lambda x: issue_pattern.sub(normalize_issue, str(x))
)
print("=== AFTER ISSUE TYPE NORMALIZATION ===")
print(df[["ticket_id", "issue_type", "issue_type_clean"]])
=== AFTER ISSUE TYPE NORMALIZATION ===
   ticket_id     issue_type issue_type_clean
0          1        billing          Billing
1          2       BILLING          Billing
2          3  Billing issue          Billing
3          4     technical        Technical

“billing,” “BILLING,” and “Billing issue” all normalized to “Billing.” The function-based re.sub() let us apply conditional logic — checking if “bill” appears in the lowercase version — rather than just doing a static string replacement.

# Step 3: Parse and normalize dates to ISO format

date_pattern = re.compile(r"""
    (?P<month_name>January|February|March|April|May|June|July|August|September|October|November|December)\s+(?P<day_mn>\d{1,2}),?\s+(?P<year_mn>\d{4})
    |
    (?P<year_iso>\d{4})-(?P<month_iso>\d{2})-(?P<day_iso>\d{2})
    |
    (?P<month_us>\d{1,2})/(?P<day_us>\d{1,2})/(?P<year_us>\d{4})
""", re.VERBOSE | re.IGNORECASE)

month_map = {
    "january": 1, "february": 2, "march": 3, "april": 4,
    "may": 5, "june": 6, "july": 7, "august": 8,
    "september": 9, "october": 10, "november": 11, "december": 12
}

def parse_date(text):
    """Parse a date string in any supported format, return ISO or None."""
    match = date_pattern.search(str(text))
    if not match:
        return None
    if match.group("month_name"):
        month = month_map[match.group("month_name").lower()]
        day = int(match.group("day_mn"))
        year = int(match.group("year_mn"))
        return f"{year}-{month:02d}-{day:02d}"
    elif match.group("year_iso"):
        return f"{match.group('year_iso')}-{match.group('month_iso')}-{match.group('day_iso')}"
    elif match.group("month_us"):
        month = int(match.group("month_us"))
        day = int(match.group("day_us"))
        year = int(match.group("year_us"))
        return f"{year}-{month:02d}-{day:02d}"
    return None

df["date_iso"] = df["date_reported"].apply(parse_date)
print("=== AFTER DATE NORMALIZATION ===")
print(df[["ticket_id", "date_reported", "date_iso"]])
=== AFTER DATE NORMALIZATION ===
   ticket_id    date_reported    date_iso
0          1       12/25/2024  2024-12-25
1          2       2024-01-15  2024-01-15
2          3  January 5, 2025  2025-01-05
3          4     Invalid date        None

Three different date formats, all normalized to ISO. The invalid date became None — no crash, no garbage data.

# Step 4: Tokenize free-text descriptions while preserving punctuation
# (Simulating a description column we'd have in real tickets)

descriptions = [
    "Cannot log in. Password reset doesn't work!",
    "Billing error: charged twice for the same month.",
    "How do I export my data? Need CSV format."
]

# Split on whitespace OR punctuation, but KEEP the punctuation as separate tokens
# The capturing group (\S) keeps the non-whitespace delimiters in the output
token_pattern = re.compile(r"(\s+|[.,!?;:])")

for i, desc in enumerate(descriptions):
    tokens = [t for t in token_pattern.split(desc) if t.strip()]
    print(f"Ticket {i+1} tokens: {tokens}")
Ticket 1 tokens: ['Cannot', 'log', 'in', '.', 'Password', 'reset', "doesn't", 'work', '!']
Ticket 2 tokens: ['Billing', 'error', ':', 'charged', 'twice', 'for', 'the', 'same', 'month', '.']
Ticket 3 tokens: ['How', 'do', 'I', 'export', 'my', 'data', '?', 'Need', 'CSV', 'format', '.']

By using re.split() with a capturing group, we kept the punctuation as separate tokens — perfect for NLP pipelines that need to distinguish words from sentence boundaries.

# Final clean DataFrame
print("=== FINAL CLEAN DATAFRAME ===")
final_df = df[["ticket_id", "phone", "email", "issue_type_clean", "date_iso"]]
print(final_df)
=== FINAL CLEAN DATAFRAME ===
   ticket_id            phone                  email issue_type_clean    date_iso
0          1  (555) 123-4567     john@example.com          Billing  2024-12-25
1          2  (555) 987-6543                 None          Billing  2024-01-15
2          3  (555) 123-4567  support@company.org          Billing  2025-01-05
3          4             None                 None        Technical        None

We started with four messy rows and ended with structured, analyzable columns. Every regex operation was compiled for performance, used re.VERBOSE for readability, and handled missing or invalid data gracefully with None instead of crashing.

Recap

We covered a lot of ground. Here’s what to remember:

  • Regex describes the shape of text, not exact characters. It’s the right tool when string methods can’t handle the variation in your data.
  • re.search() vs. re.match(): search() finds a pattern anywhere; match() only checks the start of the string. For data cleaning, you almost always want search().
  • findall() changes its return type depending on how many capturing groups you have. Use finditer() when you need consistent match objects.
  • Named groups ((?P<name>...)) turn cryptic index-based extraction into self-documenting code. Your future self will thank you.
  • Greedy quantifiers are the most common regex bug. Add ? after a quantifier to make it lazy and match as little as possible.
  • re.VERBOSE is the single most important flag for any pattern you’ll need to debug later. Whitespace and comments inside your pattern are free.
  • Compile your patterns when you’re applying them to thousands of rows. It’s a simple performance win.
  • Every pattern has limitations. Be honest about when your regex will break, and don’t try to solve RFC-compliant email validation with regex alone.

Check Your Understanding

Remember: What’s the difference between re.search() and re.match()? When would you use each in a data-cleaning context?

Understand: Why does re.findall() return a list of tuples when your pattern has two capturing groups, but a list of strings when it has one? Explain the behavior in plain English.

Apply: Write a regex pattern that extracts all words starting with a capital letter from a sentence. Test it on: "Alice and Bob went to Chicago last Tuesday."

Analyze: Given the pattern r"<.*>" and the string "<div>content</div>", what will it match? Why? What would you change to match each tag separately?

Evaluate: A colleague writes re.match(r"Error", log_line) to find error messages in a log file where each line starts with a timestamp like [2024-01-15 14:30:00] Error: .... Will this work? If not, what should they use instead?

Create: Design a regex pattern that extracts product codes from a string where codes follow the format ABC-1234 (three uppercase letters, a hyphen, four digits) but may be surrounded by other text. Use named groups and re.VERBOSE. Test it on: "Order contains: XYZ-9876 and ABC-1234 (backordered)."

Apply What You Learned

Take a CSV with a single column called `raw_contact` that contains entries like `"John Doe | (555) 123-4567"`, `"Jane: jane@site.org"`, and `"No contact info available"`. Write a Python script that: - Extracts names (anything before an email in angle brackets, or before a colon) - Extracts emails using a compiled, VERBOSE pattern with a named group - Extracts phone numbers using a compiled, VERBOSE pattern with named groups for area code, exchange, and subscriber - Outputs a clean DataFrame with columns `name`, `email`, and `phone`, using `None` where information is missing.

Deliverable: A single, self-contained Python script that reads the messy data, applies the cleaning, and prints the clean DataFrame.

Self-check rubric:

  • Are all patterns compiled with re.compile()?
  • Does the email pattern use re.VERBOSE and a named group?
  • Does the phone pattern use re.VERBOSE and named groups for each part?
  • Are missing values handled gracefully (returning None instead of crashing)?
  • Does the script run without errors and produce a DataFrame with three clean columns?
  • Python Engineering Under review

    Regular Expressions For Data Cleaning The Patterns

    messy_data = pd.DataFrame({ 'name': ['Alice Johnson', 'Bob Smith ', ' Charlie Brown', 'Diana Prince', 'Eve Davis'], 'phone': ['(555) 123-4567', '555.123.

  • Python Engineering Under review

    Data Visualization Libraries Reference Matplotlib

    Before we compare APIs, we need to talk about something most tutorials skip entirely: **what happens when you call `.show()`?**

  • Python Engineering Under review

    Pandas Groupby Reference Every Pattern You Ll Actu

    np.random.seed(42) n = 1000 df = pd.DataFrame({ 'region': np.random.choice(['North', 'South', 'East', 'West'], n), 'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n), 'revenue': np.random.

  • Python Engineering Under review

    Linters Type Checkers And Formatters For Python Da

    data = { "product": ["A", "B", "C"], "sales": ["100", "200", "invalid"] # strings from a messy CSV } df = pd.DataFrame(data)

Looking for something else?

Search every article by title, summary or topic.