Regular Expressions Cheat Sheet: 20 Patterns You Use 80% of the Time
Regex is powerful but notoriously hard to read. This guide covers the 20 most common patterns with copy-paste examples you can use immediately in your projects.
Basic Building Blocks
Before diving into patterns, understand these essentials:
.— Any character except newline\d— Any digit (0-9)\w— Any word character (a-z, A-Z, 0-9, _)\s— Whitespace (space, tab, newline)^— Start of string$— End of string[abc]— Any of a, b, or c[^abc]— NOT a, b, or c|— OR (alternation)()— Capture group(?:)— Non-capturing group
1. Email Address
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;Validates the basic structure of most email addresses. For production, note that truly validating email requires sending a confirmation — no regex is perfect.
2. URL
const urlRegex = /^https?:\/\/[^\s/$.?#].[^\s]*$/i;Matches http and https URLs. The i flag makes it case-insensitive.
3. Phone Number (US Format)
const phoneRegex = /^\+?1?\s*\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;Matches formats like: +1 (555) 123-4567, 555-123-4567, 5551234567
4. Date (YYYY-MM-DD)
const dateRegex = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;Validates ISO 8601 date format. This pattern also validates month and day ranges (won't accept Feb 31).
5. Time (HH:MM or HH:MM:SS)
const timeRegex = /^([01]\d|2[0-3]):([0-5]\d)(:[0-5]\d)?$/;Matches 24-hour time format. Optional seconds.
6. Hex Color Code
const hexRegex = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;Matches #RGB or #RRGGBB format. The # is optional.
7. IPv4 Address
const ipRegex = /^(?:(?:25[0-5]|2[0-4]\d|1?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1?\d\d?)$/;Matches valid IPv4 addresses from 0.0.0.0 to 255.255.255.255
8. Username (alphanumeric, 3-16 chars)
const usernameRegex = /^[a-zA-Z0-9_]{3,16}$/;Letters, numbers, and underscores only. Length between 3 and 16.
9. Strong Password
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$/;Requires: lowercase, uppercase, digit, special char, minimum 8 characters. Uses lookahead assertions.
10. Credit Card Number (basic validation)
const ccRegex = /^(?:4[0-9]{12}|5[1-5][0-9]{14}|3[47][0-9]{13})$/;Validates Visa, MasterCard, and Amex formats. Does not verify the checksum (Luhn algorithm).
Advanced Patterns
11. Password with Special Characters Only
const strongPwdRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$/;Requires: lowercase, uppercase, digit, special char, minimum 8 characters. Uses lookahead assertions.
12. Credit Card Number (basic validation)
const ccRegex = /^(?:4[0-9]{12}|5[1-5][0-9]{14}|3[47][0-9]{13})$/;Validates Visa, MasterCard, and Amex formats. Does not verify the checksum (Luhn algorithm).
13. Slug / URL-Friendly String
const slugRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;Lowercase letters, numbers, single hyphens between words. No leading/trailing hyphens. Perfect for URL segments like my-blog-post.
14. HTML Tag Matcher
const htmlTagRegex = /<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/;Matches opening tags with content and closing tags, or self-closing tags. Useful for basic HTML parsing.
15. Comma-Separated Numbers
const commaNumRegex = /^\d{1,3}(,\d{3})*$/;Matches properly formatted numbers: 1,000, 1,000,000 but not 10,00 or 1000,000.
16. Social Security Number (US)
const ssnRegex = /^\d{3}-\d{2}-\d{4}$/;Matches format XXX-XX-XXXX. For production validation, also verify the SSN ranges (Area: 001-899, Group: 01-99, Serial: 0001-9999).
17. ZIP Code (US)
const zipRegex = /^\d{5}(-\d{4})?$/;Matches 5-digit ZIP codes and ZIP+4 format (12345-6789).
18. MAC Address
const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;Matches MAC addresses in formats like 00:1B:44:11:3A:B7 or 00-1B-44-11-3A-B7.
19. JWT Token
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+$/;Basic JWT format validation. Checks for three base64url-encoded parts separated by dots.
20. ISBN-10 or ISBN-13
const isbnRegex = /^(?:\d{9}[\dXx]|\d{13})$/;Matches both ISBN-10 and ISBN-13 formats. ISBN-10 uses digits + optional X as check digit.
Regex Flags Explained
Flags modify how the regex engine interprets the pattern:
g— Global: Find all matches, not just the firsti— Case-insensitive: Match both upper and lowercasem— Multiline:^and$match line starts/endss— Dotall:.matches newlines toou— Unicode: Enable full Unicode support
Quick Reference: Quantifiers
*— 0 or more (greedy)+— 1 or more (greedy)?— 0 or 1 (optional){n}— Exactly n{n,}— n or more{n,m}— Between n and m*?,+?,??— Lazy versions (match as few as possible)
Lookahead and Lookbehind
Lookaheads and lookbehinds let you assert patterns without consuming characters:
(?=abc)— Positive lookahead: must be followed by "abc"(?!abc)— Negative lookahead: must NOT be followed by "abc"(?<=abc)— Positive lookbehind: must be preceded by "abc"(?<!abc)— Negative lookbehind: must NOT be preceded by "abc"
// Example: Match price without currency symbol
const priceRegex = /(?<=\$)\d+\.\d{2}/;
// Matches "12.34" in "$12.34" without capturing the $Common Use Cases in JavaScript
Validating Form Input
function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
// Usage
validateEmail("user@example.com"); // true
validateEmail("invalid-email"); // falseExtracting Data
// Extract all numbers from a string
const str = "Order #12345 shipped on 2024-01-15";
const numbers = str.match(/\d+/g);
// Result: ["12345", "2024", "01", "15"]
// Extract matches with capture groups
const log = "Error: 404 Not Found";
const [, code, message] = log.match(/Error: (\d+) (.+)/);
// code = "404", message = "Not Found"Search and Replace
// Replace all phone numbers with [REDACTED]
const text = "Call 555-123-4567 or 555-987-6543";
const sanitized = text.replace(/\d{3}-\d{3}-\d{4}/g, "[REDACTED]");
// Result: "Call [REDACTED] or [REDACTED]"
// Convert camelCase to kebab-case
const camelCase = "firstName";
const kebabCase = camelCase.replace(/([A-Z])/g, '-$1').toLowerCase();
// Result: "first-name"Performance Tips
- Be specific:
\d{4}is faster than[0-9]{4} - Avoid catastrophic backtracking: Don't use nested quantifiers like
(a+)+ - Use anchors: Start with
^and end with$when matching entire strings - Prefer character classes:
[a-z]over alternation(a|b|c|...|z) - Compile once: Store regex in variables outside loops
Try These Patterns Live
Test any of these patterns instantly in the Regex Tester tool. Paste your test string, enter the pattern, toggle flags (g, i, m), and see matches highlighted in real time.