Regex Cheat Sheet: Common Patterns Every Developer Needs
A practical reference of regex patterns for email validation, password strength, phone numbers, dates, and more. Copy-paste examples included.
Regular expressions are one of those tools that every developer needs but few have fully memorized. Whether you're validating user input, parsing log files, or doing search-and-replace across a codebase, the right regex pattern saves hours of manual work. This cheat sheet covers the patterns you'll actually use day to day, with copy-paste examples you can drop straight into your code.
Regex Basics: The Building Blocks
Before diving into specific patterns, here's a quick refresher on the fundamental metacharacters that make regex work.
| Symbol | Meaning | Example |
|---|---|---|
. | Any character except newline | a.c matches "abc", "a1c" |
^ | Start of string | ^Hello matches "Hello world" |
$ | End of string | world$ matches "Hello world" |
* | Zero or more of the previous | ab*c matches "ac", "abc", "abbc" |
+ | One or more of the previous | ab+c matches "abc", "abbc" (not "ac") |
? | Zero or one of the previous | colou?r matches "color" and "colour" |
\d | Any digit (0-9) | \d3 matches "123" |
\w | Word character (a-z, A-Z, 0-9, _) | \w+ matches "hello_world" |
\s | Whitespace (space, tab, newline) | \s+ matches any whitespace run |
Email and URL Validation Patterns
Email validation with regex is a surprisingly deep topic. The RFC-compliant pattern is absurdly long. In practice, this simplified version catches the vast majority of valid email addresses while rejecting obvious garbage.
// Basic email validation
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
// Breakdown:
// ^[a-zA-Z0-9._%+-]+ - Local part: letters, digits, dots, underscores, etc.
// @ - The @ symbol
// [a-zA-Z0-9.-]+ - Domain name: letters, digits, dots, hyphens
// \.[a-zA-Z]{2,}$ - TLD: dot followed by 2+ lettersFor URL matching, this pattern handles most common cases including optional protocol, subdomains, and paths:
// URL validation ^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$ // Matches: // https://example.com // http://sub.example.com/path?q=1 // example.com/page
Test these patterns instantly with the Regex Tester or validate email addresses using the Email Validator.
Number and Date Patterns
Matching numbers sounds simple until you need to handle decimals, negatives, thousands separators, or specific ranges. Here are the patterns that cover real-world scenarios.
// Integer (positive or negative)
^-?\d+$
// Decimal number (optional decimal part)
^-?\d+(\.\d+)?$
// Number with commas (e.g., 1,234,567.89)
^-?\d{1,3}(,\d{3})*(\.\d+)?$
// Date: YYYY-MM-DD
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
// Date: MM/DD/YYYY
^(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])\/\d{4}$
// Time: HH:MM (24-hour)
^([01]\d|2[0-3]):[0-5]\d$
// Time: HH:MM:SS with optional AM/PM
^(0?[1-9]|1[0-2]):[0-5]\d(:[0-5]\d)?\s?(AM|PM|am|pm)?$Note that regex date validation only checks the format, not whether the date is actually valid. February 30th would pass the format check. For real date validation, parse the string with your language's date library after the regex confirms the format.
Password Strength and Input Validation
Password requirements are a common use case for regex. Here are patterns for various strength levels, from basic to strict.
// Minimum 8 characters
^.{8,}$
// At least one uppercase, one lowercase, one digit, min 8 chars
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$
// Strong: uppercase, lowercase, digit, special char, min 12 chars
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{12,}$
// Username: alphanumeric + underscore, 3-20 chars
^[a-zA-Z0-9_]{3,20}$
// Slug (URL-friendly string)
^[a-z0-9]+(-[a-z0-9]+)*$
// Hex color code
^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$The (?=...) syntax is a lookahead assertion. It checks whether a condition is true at a given position without consuming characters. Stacking multiple lookaheads lets you enforce several requirements at once, regardless of the order characters appear in the string.
Need to generate secure passwords to test against? Try the Slugify tool to create URL-friendly strings from any text.
Search and Replace Patterns
Regex really shines when you need to transform text, not just match it. Capture groups let you reference matched parts in the replacement string.
// Swap first and last name
// Input: "Smith, John"
// Pattern: ^(\w+),\s*(\w+)$
// Replace: $2 $1
// Output: "John Smith"
// Convert dates from MM/DD/YYYY to YYYY-MM-DD
// Pattern: (\d{2})\/(\d{2})\/(\d{4})
// Replace: $3-$1-$2
// Remove duplicate whitespace
// Pattern: \s+
// Replace: (single space)
// Wrap words in HTML tags
// Pattern: \b(\w+)\b
// Replace: <span>$1</span>
// Extract domain from email
// Pattern: @([\w.-]+)
// Group 1 captures the domain
// Remove HTML tags
<[^>]*>Capture groups are numbered starting at 1, based on the order of their opening parentheses. Named groups like (?<name>...) make complex patterns more readable, especially when you have more than three or four groups.
Phone Numbers, IPs, and Other Formats
These patterns handle common data formats you'll encounter in web applications and data processing.
// US phone number (flexible format)
^\+?1?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
// Matches: (555) 123-4567, 555-123-4567, +1 555 123 4567
// IPv4 address
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$
// IPv4 with CIDR notation
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)\/(3[0-2]|[12]?\d)$
// MAC address
^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$
// Credit card number (basic, spaces or dashes allowed)
^\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}$
// SSN format (US)
^\d{3}-\d{2}-\d{4}$
// ZIP code (US, with optional +4)
^\d{5}(-\d{4})?$Common Pitfalls and Tips
After years of debugging regex issues, these are the mistakes that come up most often.
- Forgetting to escape special characters: Dots, parentheses, brackets, and backslashes all have special meaning. Use
\.to match a literal dot. - Greedy vs. lazy matching: By default,
.*is greedy and matches as much as possible. Add?to make it lazy:.*?matches as little as possible. This matters when parsing HTML or extracting quoted strings. - Not anchoring your patterns: Without
^and$, your pattern can match a substring instead of the whole string./\d+/matches the "123" inside "abc123def". - Catastrophic backtracking: Nested quantifiers like
(a+)+$can cause exponential matching time on certain inputs. Avoid nesting*and+inside groups that also repeat. - Testing only the happy path: Always test your regex against edge cases, empty strings, and intentionally malformed input.
The best way to build and debug regex is interactively. Paste your pattern and test strings into the Regex Tester to see matches highlighted in real time, with capture group breakdowns and detailed explanations of what each part of your pattern does.