A U.S. phone number can appear with parentheses, dashes, dots, or spaces. Python regex can extract these variants, normalize them, and prepare their components for downstream data use. section 4.3 section 4.3.1
A practical processing workflow:
- Extract numbers from text with a regex that accepts common U.S. separators and optional parentheses. section 4.3.1
- Normalize each match by removing non-digits and formatting valid 10-digit values as +1-XXX-XXX-XXXX. section 4.3.2
- Use capture groups to split values into area_code, first_3, and last_4 fields for DataFrame or JSON output. section 4.3.3
- Test regex against real samples and review matches because extensions, country codes, international numbers, and invalid lookalikes can break brittle patterns. section 4.3.3
Common formats
The values (212) 555-7890, 646-123-4567, and 917.555.1234 can be extracted from one text block, normalized to +1-212-555-7890, +1-646-123-4567, and +1-917-555-1234, then decomposed into three numeric fields. section 4.3.1 section 4.3.2
import re
import pandas as pd
text = """
Call me at (212) 555-7890. My backup number is 646-123-4567. You can also reach me at 917.555.1234.
"""
# Regex with capture groups for structured output
matches = re.findall(r'\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})', text)
# Convert to DataFrame
df = pd.DataFrame(matches, columns=["Area Code", "First 3", "Last 4"])
display(df)
A complete Python pattern uses capture groups and pandas to turn extracted U.S. phone numbers into structured columns. section 4.3.3
