Regular expressions are one of the most powerful tools in a developer's arsenal — and one of the most frustrating to get right. This cheat sheet covers the patterns you'll actually use in real projects, with explanations for each.
Essential Syntax
Before diving into patterns, here's a quick refresher on the building blocks:
.— matches any single character (except newline)*— zero or more of the preceding element+— one or more of the preceding element?— zero or one of the preceding element (makes it optional)^— start of string,$— end of string[abc]— character class (matches a, b, or c)[^abc]— negated class (matches anything except a, b, or c)\d— digit,\w— word character,\s— whitespace(group)— capturing group,(?:group)— non-capturing group
Email Address
A practical email regex that covers the vast majority of real-world addresses:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
This matches standard email formats like user@example.com and
first.last+tag@sub.domain.co.uk. For production validation, combine
regex with server-side verification.
URL
Match HTTP and HTTPS URLs:
https?:\/\/[\w\-]+(\.[\w\-]+)+[\/\w\-._~:?#\[\]@!$&'()*+,;=]*
Phone Number (US)
Matches common US phone formats like (555) 123-4567, 555-123-4567, and 5551234567:
^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
IP Address (IPv4)
Matches valid IPv4 addresses like 192.168.1.1:
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$
Hex Color Code
Matches 3-digit and 6-digit hex colors like #fff and #1a2b3c:
^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
Password Strength
Requires at least 8 characters, one uppercase, one lowercase, one digit, and one special character:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Date (YYYY-MM-DD)
Matches ISO 8601 date format:
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
Testing Your Patterns
Writing regex is only half the battle — testing it with real data is essential. Use a regex tester to paste your pattern and test strings, see matches highlighted in real time, and catch edge cases before they reach production. Testing in a dedicated tool is dramatically faster than running your application repeatedly.