Regex Patterns Every Developer Should Know
Regex Patterns Every Developer Should Know
Regular expressions are one of the most powerful tools in a developer's toolkit, but their terse syntax makes them intimidating. This guide covers the patterns you will actually use in production, with clear explanations.
Email Validation (Practical)
The fully RFC-compliant email regex is over 6,000 characters. In practice, use a simple pattern and verify with a confirmation email.
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
This catches most valid emails without false positives on clearly invalid input.
URL Extraction
Pull URLs from text content:
https?:\/\/[^\s<>"{}|\\^\x60]+
This matches http and https URLs up to the first whitespace or special delimiter.
Semantic Version Matching
Parse semver strings like 2.14.3 or 1.0.0-beta.1:
^(\d+)\.(\d+)\.(\d+)(?:-([-\w.]+))?(?:\+([\w.]+))?$
Capture groups give you major, minor, patch, pre-release, and build metadata.
IP Address Validation
IPv4 with proper range checking:
^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$
Note: a naive \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} matches invalid IPs like 999.999.999.999.
Password Strength
Require at least 8 characters with one uppercase, one lowercase, one digit, and one special character:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Lookaheads (?=) check conditions without consuming characters, allowing all checks at position zero.
UUID Detection
Match UUID v4 format:
[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}
The 4 in the third group and [89ab] in the fourth group are specific to UUID v4.
Whitespace Cleanup
Collapse multiple spaces into one:
\s{2,}
Replace with a single space. Use ^\s+|\s+$ to trim leading and trailing whitespace.
Common Mistakes to Avoid
Greedy matching:.* is greedy by default. Use .*? for non-greedy matching when extracting content between delimiters.
// Greedy (matches too much):
/
.*<\/div>/ // Matches from first to LAST
// Non-greedy (matches correctly):
/
.*?<\/div>/ // Matches from first to NEXT
Backtracking: Complex patterns with nested quantifiers like (a+)+ can cause catastrophic backtracking. Always test regex performance with long inputs.
Not escaping special characters: Characters like ., *, +, ?, and | have special meaning. Escape them with \\ when matching literally.
Conclusion
You do not need to memorize every regex feature. Keep this reference handy, use a regex tester tool to build and debug patterns, and always add comments explaining what complex patterns match. Future you will be grateful.