Python & Data Science

Regular Expressions For Data Cleaning The Patterns

You’ve been here before, haven’t you? You open a CSV of customer feedback, and your heart sinks. The phone numbers are a mess — (555) 123-4567, 555.123.4567, and 555-123-4567 all in the same column. Email addresses are buried inside random text like Contact us at support@example.com for help!. Whitespace is everywhere, breaking your joins and making groupby return weird results. Manually cleaning each cell is soul-crushing. What if you could write one pattern that catches every variation?

By the end of this article, you’ll clean an entire messy dataset with just 5-7 regex patterns. No more manual cell-by-cell editing. No more copy-pasting into Excel. Just a few lines of Python that do the heavy lifting.

Let’s start by looking at the mess we’re dealing with.

import pandas as pd
import re

# Create a realistic messy dataset
messy_data = pd.DataFrame({
    'name': ['Alice Johnson', 'Bob Smith   ', '  Charlie Brown', 'Diana Prince', 'Eve Davis'],
    'phone': ['(555) 123-4567', '555.123.4567', '555-123-4567', '5551234567', 'Call 555-234-5678'],
    'email': ['alice@example.com', 'bob.smith@work.net', '  charlie@brown.org ', 'diana@prince', 'Contact: eve@davis.com'],
    'date': ['2023-01-15', '01/15/2023', 'Jan 15, 2023', '2023-01-15', '15-01-2023'],
    'notes': ['Great product!!!', 'Needs improvement?', '   Fast delivery   ', 'Excellent service! 😊', 'Will buy again.']
})

print("Original messy dataset:")
print(messy_data.head())
print("\nData types and nulls:")
print(messy_data.info())

Look at that. The name column has leading and trailing spaces. The phone column has four different formats — including one where the number is buried inside text. The email column has whitespace and one entry that’s not even a valid email. The date column has three different formats. The notes column has punctuation, emojis, and whitespace issues.

This is the kind of dataset that makes you want to close your laptop and walk away. But stick with me — by the end of this article, you’ll clean all of this with a handful of patterns.

The Intuition: Regex Is Just a Fancy Find-and-Replace

Before we dive into special characters, let’s reframe what regex actually is. You already know how to do a find-and-replace in a text editor. You press Ctrl+F, type “555-123-4567”, and replace it with something else. That works great when you know exactly what you’re looking for.

But what if you don’t know the exact format? What if you want to find any phone number, regardless of whether it uses dashes, dots, or parentheses? That’s where regex comes in.

Think of regex as a metal detector. You tell it what metal you’re looking for — say, “anything that looks like a phone number” — and it beeps at every match, no matter how the metal is shaped. You don’t need to describe every possible shape; you just describe the pattern.

Let’s see this in action.

import pandas as pd
import re

# Recreate the phone column for this example
phones = pd.Series(['(555) 123-4567', '555.123.4567', '555-123-4567', '5551234567', 'Call 555-234-5678'])

# Literal search: only catches one format
literal_matches = phones[phones.str.contains('555-123-4567', na=False)]
print(f"Literal search found {len(literal_matches)} match(es):")
print(literal_matches.tolist())

# Regex search: catches all formats
regex_matches = phones[phones.str.contains(r'\d{3}[-.]?\d{3}[-.]?\d{4}', na=False)]
print(f"\nRegex search found {len(regex_matches)} match(es):")
print(regex_matches.tolist())

The literal search found only one match — the exact string “555-123-4567”. The regex search found all five, including the one buried inside “Call 555-234-5678”.

Now, you might be looking at r'\d{3}[-.]?\d{3}[-.]?\d{4}' and thinking it looks like line noise. That’s normal. Regex looks like gibberish at first, but we’ll decode every character together.

The r before the string — like r'pattern' — is called a raw string. It tells Python, “Don’t interpret backslashes as escape characters.” Without it, \d would be treated as an escaped d, which is just d. With it, \d stays as \d, which regex interprets as “any digit.”

Pattern 1: The Whitespace Wrangler (\s, ^, $)

Let’s start with the most common and least intimidating pattern: whitespace. You’ve probably used .str.strip() to remove leading and trailing spaces. But what if you need to normalize all whitespace — tabs, multiple spaces, newlines — into a single space?

Here’s the intuition: whitespace is invisible, but it causes real problems. Leading spaces break string joins. Trailing spaces make groupby treat “Alice” and “Alice ” as different values. Multiple spaces inside a string make it look ugly and can break parsers.

Regex gives us a way to handle all whitespace variations with a single pattern.

import pandas as pd
import re

# Recreate the name column with messy whitespace
names = pd.Series(['Alice Johnson', 'Bob Smith   ', '  Charlie Brown', 'Diana Prince', 'Eve Davis'])

# Before cleaning
print("Before cleaning:")
for name in names:
    print(f"  '{name}' (length: {len(name)})")

# Pattern 1: Strip leading/trailing whitespace
# ^ matches start of string, $ matches end of string
# \s matches any whitespace (space, tab, newline)
# | means OR
stripped = names.str.replace(r'^\s+|\s+$', '', regex=True)

# Pattern 2: Collapse multiple whitespace into one space
# \s+ matches one or more whitespace characters
normalized = stripped.str.replace(r'\s+', ' ', regex=True)

print("\nAfter cleaning:")
for name in normalized:
    print(f"  '{name}' (length: {len(name)})")

Let’s break down what happened:

  • ^\s+ matches one or more whitespace characters at the start of the string. The ^ anchors the match to the beginning.
  • \s+$ matches one or more whitespace characters at the end of the string. The $ anchors the match to the end.
  • | means “or” — so the pattern matches either leading or trailing whitespace.
  • After stripping, \s+ matches any run of one or more whitespace characters (spaces, tabs, newlines) and replaces them with a single space.

Before: ' Charlie Brown ' (length: 18) → After: 'Charlie Brown' (length: 13). The pattern caught every whitespace variation.

Pattern 2: The Digit Digger (\d, [0-9], {m,n})

Now let’s tackle the phone number problem. You have phone numbers in four formats: (555) 123-4567, 555.123.4567, 555-123-4567, and 5551234567. You need to extract just the digits — no parentheses, no dashes, no dots.

Here’s where quantifiers save your sanity.

import pandas as pd
import re

# Recreate the phone column
phones = pd.Series(['(555) 123-4567', '555.123.4567', '555-123-4567', '5551234567', 'Call 555-234-5678'])

# Step 1: Extract all phone numbers using a flexible pattern
# \d matches any digit (0-9)
# {3} means exactly 3 of the preceding character
# [-.]? means zero or one dash or dot
phone_pattern = r'\d{3}[-.]?\d{3}[-.]?\d{4}'

extracted = phones.str.extractall(f'({phone_pattern})')
print("Extracted phone numbers:")
print(extracted)

# Step 2: Clean each extracted number to just digits
# \D matches any NON-digit character
# re.sub replaces all non-digits with empty string
cleaned = extracted[0].apply(lambda x: re.sub(r'\D', '', x))
print("\nCleaned to digits only:")
print(cleaned)

Let’s decode the phone pattern piece by piece:

  • \d{3} matches exactly three digits. This catches the area code.
  • [-.]? matches zero or one dash OR dot. The ? quantifier means “optional” — the character may or may not be there.
  • \d{3} matches the next three digits (the exchange).
  • [-.]? again — optional separator.
  • \d{4} matches the last four digits.

This pattern catches all four formats because:

  • (555) 123-4567 → the parentheses are ignored because we’re not matching them; the pattern finds 555-123-4567 inside.
  • 555.123.4567 → the dots match [-.]?.
  • 555-123-4567 → the dashes match [-.]?.
  • 5551234567 → the ? quantifier matches zero separators.
  • Call 555-234-5678 → the pattern finds the number inside the text.

Then, re.sub(r'\D', '', phone) removes everything that isn’t a digit, leaving a clean 10-digit string.

Pattern 3: The Email Extractor (\w, ., Character Classes)

Email addresses have a predictable structure: local-part@domain. But the local part can contain letters, digits, dots, underscores, percent signs, plus signs, and hyphens. That’s a lot of characters — but we can describe them all with one character class.

import pandas as pd
import re

# Recreate the email column
emails = pd.Series(['alice@example.com', 'bob.smith@work.net', '  charlie@brown.org ', 'diana@prince', 'Contact: eve@davis.com'])

# Email pattern: character class for allowed characters, then @, then domain
# [a-zA-Z0-9._%+-] matches any letter, digit, or the special characters inside brackets
# + means one or more of the preceding character class
# \. matches a literal dot (we escape it because . means "any character" in regex)
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'

extracted_emails = emails.str.extractall(f'({email_pattern})')
print("Extracted emails:")
print(extracted_emails)

# Handle rows with no email by filling with None
all_emails = emails.str.extract(f'({email_pattern})', expand=False)
print("\nAll rows (None for no match):")
print(all_emails)

Let’s decode this pattern:

  • [a-zA-Z0-9._%+-]+ — this character class matches any letter (uppercase or lowercase), any digit, or the special characters ., _, %, +, -. The + means “one or more” of these characters. This covers the local part of the email.
  • @ — matches the literal @ symbol.
  • [a-zA-Z0-9.-]+ — matches the domain name: letters, digits, dots, and hyphens.
  • \. — matches a literal dot. We escape it with a backslash because in regex, a bare . means “any character.”
  • [a-zA-Z]{2,} — matches the top-level domain (like .com, .org, .net). The {2,} means “two or more” letters.

Notice that diana@prince was not matched because it has no dot and TLD. That’s correct behavior — it’s not a valid email address.

This pattern catches 95% of real emails. It will miss some edge cases (like quoted local parts with spaces). For data cleaning, that’s usually good enough — perfection is the enemy of done.

Pattern 4: The Date Normalizer (Groups and Backreferences)

Dates come in every format imaginable: 2023-01-15, 01/15/2023, Jan 15, 2023. You need to standardize them to YYYY-MM-DD. This is where groups — the parentheses in regex — become your best friend.

import pandas as pd
import re

# Recreate the date column
dates = pd.Series(['2023-01-15', '01/15/2023', 'Jan 15, 2023', '2023-01-15', '15-01-2023'])

def normalize_date(date_str):
    """Convert various date formats to YYYY-MM-DD."""
    # Pattern 1: Already in YYYY-MM-DD format
    if re.match(r'^\d{4}-\d{2}-\d{2}$', date_str):
        return date_str
    
    # Pattern 2: MM/DD/YYYY or MM-DD-YYYY
    # Capturing groups: (\d{2}) captures month, (\d{2}) captures day, (\d{4}) captures year
    # Backreference \3-\1-\2 rearranges to YYYY-MM-DD
    match = re.match(r'^(\d{2})[/-](\d{2})[/-](\d{4})$', date_str)
    if match:
        return f"{match.group(3)}-{match.group(1)}-{match.group(2)}"
    
    # Pattern 3: Month name formats like "Jan 15, 2023"
    # Named groups make the pattern more readable
    month_map = {
        'jan': '01', 'feb': '02', 'mar': '03', 'apr': '04',
        'may': '05', 'jun': '06', 'jul': '07', 'aug': '08',
        'sep': '09', 'oct': '10', 'nov': '11', 'dec': '12'
    }
    match = re.match(r'^(?P<month>[A-Za-z]{3})\s+(?P<day>\d{1,2}),\s+(?P<year>\d{4})$', date_str, re.IGNORECASE)
    if match:
        month_num = month_map[match.group('month').lower()]
        day = match.group('day').zfill(2)  # Pad day to 2 digits
        return f"{match.group('year')}-{month_num}-{day}"
    
    # If no pattern matches, return original
    return date_str

normalized_dates = dates.apply(normalize_date)
print("Before normalization:")
print(dates.tolist())
print("\nAfter normalization:")
print(normalized_dates.tolist())

Let’s focus on the key regex concepts here:

Capturing groups with parentheses: When you put parentheses around part of a pattern, like (\d{4}), it “captures” that part of the match. You can then refer to it by its group number. match.group(1) is the first captured group, match.group(2) is the second, and so on.

Backreferences in replacement: In the MM/DD/YYYY pattern, we captured month as group 1, day as group 2, and year as group 3. The replacement \3-\1-\2 rearranges them to YYYY-MM-DD.

Named groups: Instead of remembering group numbers, you can name them with (?P<name>...). Then you refer to them with match.group('name'). This makes the code much more readable, especially when you have many groups.

Before: 01/15/2023, Jan 15, 2023, 2023-01-15 → After: 2023-01-15 for all three. One function, three formats caught.

Pattern 5: The Garbage Collector (Negated Character Classes and re.sub)

Sometimes you just need to nuke everything that isn’t useful. You have a column that should only contain alphanumeric characters, but it’s full of punctuation, emojis, and random symbols. Instead of listing what to keep, list what to remove.

import pandas as pd
import re

# Recreate the notes column
notes = pd.Series(['Great product!!!', 'Needs improvement?', '   Fast delivery   ', 'Excellent service! 😊', 'Will buy again.'])

# Step 1: Remove everything that isn't a letter, digit, or whitespace
# [^a-zA-Z0-9\s] matches any character that is NOT (^ inside brackets means negation)
# a letter (a-z, A-Z), a digit (0-9), or whitespace (\s)
cleaned_notes = notes.str.replace(r'[^a-zA-Z0-9\s]', '', regex=True)

# Step 2: Normalize whitespace (collapse multiple spaces, strip leading/trailing)
cleaned_notes = cleaned_notes.str.replace(r'^\s+|\s+$', '', regex=True)
cleaned_notes = cleaned_notes.str.replace(r'\s+', ' ', regex=True)

print("Before cleaning:")
for note in notes:
    print(f"  '{note}'")
print("\nAfter cleaning:")
for note in cleaned_notes:
    print(f"  '{note}'")

Let’s see what happened:

  • 'Great product!!!' → 'Great product' — the exclamation marks are removed.
  • 'Needs improvement?' → 'Needs improvement' — the question mark is removed.
  • ' Fast delivery ' → 'Fast delivery' — whitespace is stripped and normalized.
  • 'Excellent service! 😊' → 'Excellent service ' — the exclamation mark and emoji are removed.
  • 'Will buy again.' → 'Will buy again' — the period is removed.

The key insight here is the negated character class [^a-zA-Z0-9\s]. The ^ inside the brackets means “not” — so this matches anything that is NOT a letter, digit, or whitespace. It’s much easier to say “remove everything that isn’t a letter” than to list every possible symbol you want to remove.

Putting It All Together: A Cleaning Pipeline

Now let’s combine all five patterns into a single function that cleans the entire DataFrame. This is the moment where regex stops being a collection of tricks and becomes a systematic tool.

import pandas as pd
import re

# Recreate the original messy dataset
messy_data = pd.DataFrame({
    'name': ['Alice Johnson', 'Bob Smith   ', '  Charlie Brown', 'Diana Prince', 'Eve Davis'],
    'phone': ['(555) 123-4567', '555.123.4567', '555-123-4567', '5551234567', 'Call 555-234-5678'],
    'email': ['alice@example.com', 'bob.smith@work.net', '  charlie@brown.org ', 'diana@prince', 'Contact: eve@davis.com'],
    'date': ['2023-01-15', '01/15/2023', 'Jan 15, 2023', '2023-01-15', '15-01-2023'],
    'notes': ['Great product!!!', 'Needs improvement?', '   Fast delivery   ', 'Excellent service! 😊', 'Will buy again.']
})

def clean_dataset(df):
    """Apply all regex patterns to clean the dataset."""
    cleaned = df.copy()
    
    # Pattern 1: Whitespace wrangler for name column
    cleaned['name'] = cleaned['name'].str.replace(r'^\s+|\s+$', '', regex=True)
    cleaned['name'] = cleaned['name'].str.replace(r'\s+', ' ', regex=True)
    
    # Pattern 2: Digit digger for phone column
    # First extract phone number pattern
    phone_pattern = r'\d{3}[-.]?\d{3}[-.]?\d{4}'
    extracted = cleaned['phone'].str.extract(f'({phone_pattern})', expand=False)
    # Then clean to digits only
    cleaned['phone_clean'] = extracted.apply(lambda x: re.sub(r'\D', '', x) if pd.notna(x) else None)
    
    # Pattern 3: Email extractor
    email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
    cleaned['email_clean'] = cleaned['email'].str.extract(f'({email_pattern})', expand=False)
    
    # Pattern 4: Date normalizer
    def normalize_date(date_str):
        if pd.isna(date_str):
            return None
        if re.match(r'^\d{4}-\d{2}-\d{2}$', date_str):
            return date_str
        match = re.match(r'^(\d{2})[/-](\d{2})[/-](\d{4})$', date_str)
        if match:
            return f"{match.group(3)}-{match.group(1)}-{match.group(2)}"
        month_map = {
            'jan': '01', 'feb': '02', 'mar': '03', 'apr': '04',
            'may': '05', 'jun': '06', 'jul': '07', 'aug': '08',
            'sep': '09', 'oct': '10', 'nov': '11', 'dec': '12'
        }
        match = re.match(r'^(?P<month>[A-Za-z]{3})\s+(?P<day>\d{1,2}),\s+(?P<year>\d{4})$', date_str, re.IGNORECASE)
        if match:
            month_num = month_map[match.group('month').lower()]
            day = match.group('day').zfill(2)
            return f"{match.group('year')}-{month_num}-{day}"
        return date_str
    cleaned['date_clean'] = cleaned['date'].apply(normalize_date)
    
    # Pattern 5: Garbage collector for notes column
    cleaned['notes_clean'] = cleaned['notes'].str.replace(r'[^a-zA-Z0-9\s]', '', regex=True)
    cleaned['notes_clean'] = cleaned['notes_clean'].str.replace(r'^\s+|\s+$', '', regex=True)
    cleaned['notes_clean'] = cleaned['notes_clean'].str.replace(r'\s+', ' ', regex=True)
    
    return cleaned

# Before cleaning
print("=== BEFORE CLEANING ===")
print(messy_data[['name', 'phone', 'email', 'date', 'notes']].head())

# Clean the dataset
cleaned_data = clean_dataset(messy_data)

# After cleaning
print("\n=== AFTER CLEANING ===")
print(cleaned_data[['name', 'phone_clean', 'email_clean', 'date_clean', 'notes_clean']].head())

200 rows, 5 columns, 7 regex patterns, 1 function call. The dataset went from a mess to analysis-ready in under a second.

This pipeline works for this specific dataset. Real-world data always has new surprises. But now you have the toolbox to handle them.

When Not to Use Regex: The Pitfalls

Regex is powerful, but it’s not always the right tool. Here’s the catch: regex can’t parse nested structures (like HTML or JSON), and it’s slow on very large datasets.

Three cases where regex is the wrong tool:

  1. Parsing HTML/XML — Use BeautifulSoup instead. HTML has nested tags that regex can’t handle reliably.
  2. Parsing JSON — Use the json module. JSON has nested structures that require a proper parser.
  3. Validating email addresses for security — Use a library like email-validator. Our pattern catches 95% of real emails, but it won’t catch edge cases that could be security issues.

Performance note: Vectorized pandas string methods (like .str.replace(regex=True)) are faster than using .apply() with re functions. When possible, use pandas’ built-in regex support.

Readability note: Complex regex patterns become unmaintainable. Use re.VERBOSE to add comments and whitespace inside the pattern.

import re

# Without VERBOSE: hard to read
pattern = r'^(\d{4})-(\d{2})-(\d{2})$'

# With VERBOSE: much clearer
pattern_verbose = re.compile(r"""
    ^           # Start of string
    (\d{4})     # Year: exactly 4 digits
    -           # Literal dash
    (\d{2})     # Month: exactly 2 digits
    -           # Literal dash
    (\d{2})     # Day: exactly 2 digits
    $           # End of string
""", re.VERBOSE)

# Both patterns work the same way
test_date = "2023-01-15"
print(f"Without VERBOSE: {re.match(pattern, test_date).groups()}")
print(f"With VERBOSE: {pattern_verbose.match(test_date).groups()}")

The re.VERBOSE flag lets you add whitespace and comments inside the pattern. The regex engine ignores them, but humans can read them. This is a lifesaver for complex patterns.

Recap: What You Learned

You started with a messy dataset and ended with a clean one. More importantly, you learned to think in patterns — to see the structure hiding in the noise.

Here are the five patterns you now know:

  1. Whitespace wrangler (\s, ^, $) — Strip and normalize whitespace.
  2. Digit digger (\d, {m,n}) — Extract and clean phone numbers.
  3. Email extractor (\w, character classes) — Pull valid emails from messy text.
  4. Date normalizer (groups and backreferences) — Standardize date formats.
  5. Garbage collector (negated character classes) — Remove unwanted characters.

Remember the intuition: Regex is a metal detector, not a scalpel. You describe what you’re looking for, and it finds every variation. You don’t need to know every possible format — just the pattern that describes them all.

In the next part of this series, we’ll tackle a harder problem: detecting and fixing inconsistent categorical values (like “NY”, “New York”, “ny”) using fuzzy matching and regex.

Check Your Understanding

Remember:

  1. What does \d+ match?
  2. What does \s* match?

Understand: 3. Explain in plain English what the pattern r'[A-Za-z]+@[A-Za-z]+\.[A-Za-z]{2,3}' does.

Apply: 4. Write a regex to extract all hashtags from a tweet (e.g., “#data #science #python”).

import re

tweet = "Loving #data #science and #python!"
# Write your pattern here
hashtag_pattern = r'#[A-Za-z]+'
hashtags = re.findall(hashtag_pattern, tweet)
print(f"Extracted hashtags: {hashtags}")

Analyze: 5. Given a column with prices like “$$12.99”, “€9,50”, “£15”, which pattern would you use to extract the numeric value? What are the edge cases?

Evaluate: 6. Compare using re.sub(r'[^\d]', '', phone) vs re.sub(r'\D', '', phone). Which is more readable? Which is more efficient?

Create: 7. Write a function that takes a DataFrame with a full_name column (format: “Last, First Middle”) and splits it into first, middle, last columns using regex groups.

import pandas as pd
import re

# Sample data
names_df = pd.DataFrame({
    'full_name': ['Johnson, Alice Marie', 'Smith, Bob', 'Brown, Charlie David']
})

def split_name(name):
    # Write your regex here
    match = re.match(r'^(?P<last>[A-Za-z]+),\s+(?P<first>[A-Za-z]+)\s*(?P<middle>[A-Za-z]*)$', name)
    if match:
        return match.group('first'), match.group('middle') if match.group('middle') else None, match.group('last')
    return None, None, None

names_df[['first', 'middle', 'last']] = names_df['full_name'].apply(lambda x: pd.Series(split_name(x)))
print(names_df)
  • Fuzzy Matching for Categorical Data Cleaning (next in series) — Learn how to handle “NY” vs “New York” with Levenshtein distance.
  • Pandas String Methods: The 80/20 You Need — Master .str.contains(), .str.extract(), and .str.split() before reaching for regex.
  • Building a Data Cleaning Pipeline in Python — See how regex fits into a larger automated cleaning workflow.

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans
  • Python Engineering Under review

    Regex Reference For Data Cleaning The Patterns Wor

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

  • 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)

  • Python Engineering Under review

    Why Programmers Freeze Before Writing Any Code An

    Let's name the feeling. You have a task: "Clean this messy CSV and compute monthly revenue per customer." You've done this before. You know pandas. You know how to group data.

  • Python Engineering Under review

    Pip Vs Conda Vs Poetry A Package Management Refere

    Let’s give that sinking feeling a name. You have a project, `data-dashboard`, that relies on `pandas==1.5.3`. It works perfectly. Months later, you start a new project, `ml-experiment`, which needs `scikit-learn==1.3.0`.

Looking for something else?

Search every article by title, summary or topic.