š» Regex Phone Number Validator
A robust regex pattern that handles multiple international phone number formats without breaking.
import re
# Comprehensive phone number validator
# Handles: US (123-456-7890), with/without parentheses, international codes
phone_pattern = re.compile(r'''
^\+? # Optional leading '+' for international
(?:\d{1,3})? # Optional country code (1-3 digits)
[\s\-\.]? # Optional separator (space, dash, or dot)
\(?\d{3}\)? # Area code with optional parentheses
[\s\-\.]? # Optional separator
\d{3} # First 3 digits
[\s\-\.]? # Optional separator
\d{4} # Last 4 digits
$''', re.VERBOSE)
def validate_phone_number(phone_str):
"""
Validate phone numbers across multiple formats.
Returns True for valid numbers, False otherwise.
"""
if not phone_str or not isinstance(phone_str, str):
return False
# Clean common separators for consistent matching
cleaned = phone_str.strip()
# Test against our comprehensive pattern
return bool(phone_pattern.match(cleaned))
# Example usage:
# print(validate_phone_number("123-456-7890")) # True
# print(validate_phone_number("(123) 456-7890")) # True
# print(validate_phone_number("+1 123.456.7890")) # True
# print(validate_phone_number("1234567890")) # True
The Problem: When Regex Becomes Regrets
Let's be honest: regex syntax wasn't designed by humans. It was clearly created by some ancient wizard who thought "Let's make a language where . means 'any character' but \. means 'literally just a dot' because why not confuse future generations?" The result is a beautiful, powerful, utterly maddening tool that can solve complex text problems in one lineāif you're willing to trade three hours of your life and your will to live.
Consider this classic developer scenario: You need to validate phone numbers. "Simple!" you think. Two hours later, you're deep in Stack Overflow threads from 2008, trying to understand why \d{3}-\d{3}-\d{4} works for American numbers but fails spectacularly when someone dares to include parentheses orāheaven forbidāan international country code. Your test suite passes, you deploy to production, and immediately get bug reports from users in Finland who apparently write phone numbers using interpretive dance notation.
The real tragedy? Regex is actually brilliant. It's compact, powerful, and when it works, it feels like magic. But the learning curve isn't a curveāit's a vertical cliff face covered in grease. You either become a regex wizard who speaks in backslashes and character classes, or you become someone who copies patterns from the internet and prays they work. There's no middle ground. Until now.
The Solution: A Translator for Regex Spirits
I built Regex Whisperer because I got tired of explaining to my rubber duck why /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/ means "password must contain uppercase, lowercase, number, and special character." The tool treats regex patterns like the temperamental spirits they areāentities that need careful coaxing, clear communication, and occasional firm talking-tos when they misbehave.
At its core, Regex Whisperer is a regex therapist. It listens to your problems ("I need to find dates in MM/DD/YYYY format but NOT if they're from before 1900"), translates them into regex language, and then explains what it created in plain English. More importantly, when your regex failsāand it willāthe tool doesn't just say "no match." It says things like "Your pattern is looking for digits, but you're feeding it letters. Maybe try \d instead of [A-Z]? Just a thought." with the sass level adjustable based on how much coffee you've had.
The magic happens through a combination of natural language processing and good old-fashioned regex expertise. You describe what you want in human terms, and the Whisperer negotiates with the regex spirits on your behalf. No more guessing whether you need a greedy or lazy quantifier. No more wondering if that backslash should be escaped. The tool handles the arcane incantations so you can focus on solving actual problems.
How to Use It: Speaking Human to Regex
Getting started is refreshingly simpleāunlike regex itself. Clone the repository, install dependencies, and you're ready to start whispering. The basic workflow goes like this: describe your problem in English, get a regex pattern, test it immediately with auto-generated test cases, and iterate if needed.
Here's the core interaction from the main file:
from regex_whisperer import RegexWhisperer
whisperer = RegexWhisperer(sass_level='medium')
# Describe what you need in plain English
pattern = whisperer.create_pattern(
"Find all Twitter handles but not if they start with 'bot_'"
)
print(f"Generated pattern: {pattern}")
# Output: @(?!bot_)[A-Za-z0-9_]{1,15}
# Get an explanation in human terms
explanation = whisperer.explain_pattern(pattern)
print(explanation)
# Output: "Matches '@' followed by 1-15 letters/numbers/underscores,
# but NOT if it starts with 'bot_' after the '@'. Because bots need
# love too, just not in your Twitter analytics."Check out the full source code on GitHub for more examples, including how to use the debugging mode that tells you exactly why your pattern is being difficult.
Key Features: What Makes This Tool Actually Useful
- Natural Language to Regex Translation: Describe what you want like you're talking to a coworker ("find URLs but skip the query parameters") and get a working pattern. The tool understands context, edge cases, and even sarcasm if you're feeling particularly frustrated.
- Regex Explanation in Plain English: Paste any regex patternāno matter how convolutedāand get a clear, concise explanation of what it actually does. Perfect for deciphering that pattern your predecessor wrote five years ago with zero comments.
- Intelligent Fixes with Sass: When patterns fail, the tool suggests specific fixes with varying levels of attitude. Set sass_level to 'polite' for professional environments or 'maximum' for when you've been debugging the same pattern since lunch.
- Automatic Test Case Generation: The tool creates relevant test strings to validate your pattern immediately. No more manually creating test cases only to realize you forgot about edge cases like empty strings or Unicode characters.
Conclusion: Stop Sacrificing Your Sanity
Regex doesn't have to be a painful rite of passage. With Regex Whisperer, you get all the power of regex patterns without the associated existential crisis. The tool won't make you a regex master overnight, but it will save you hours of trial-and-error, reduce your Stack Overflow dependency, and maybeājust maybeāmake regex enjoyable instead of terrifying.
Try it out: https://github.com/BoopyCode/regex-gpt-whisperer
Remember: regex patterns are just text processors with attitude problems. Now you have a tool that speaks their language. Your sanity will thank you, and your rubber duck can finally get some rest.
Quick Summary
- What: Regex Whisperer translates natural language to regex patterns, explains existing patterns in plain English, and fixes broken regex with sass.
š¬ Discussion
Add a Comment