20 Regex Patterns Every Developer Needs — Reference Guide
Introduction
Regular expressions (regex) are one of the most powerful tools in a developer's toolkit. Whether you are validating user input, extracting data from text, or performing search-and-replace operations, knowing the right regex pattern can save hours of work.
In this guide, we cover 20 practical regex patterns that every developer should know, with working code examples in JavaScript and Python.
1. Email Address Validation
Email validation is one of the most common uses of regex. While a perfect email regex is notoriously complex, this pattern handles 99% of real-world cases.
Pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRegex.test('user@example.com')); // true
console.log(emailRegex.test('invalid-email')); // false
import re
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
print(bool(re.match(email_pattern, 'user@example.com'))) # True
How it works: This pattern breaks down into three parts — the local part ([a-zA-Z0-9._%+-]+), the domain name ([a-zA-Z0-9.-]+), and the TLD ([a-zA-Z]{2,}).
2. URL Matching
Match HTTP and HTTPS URLs, including optional subdomains and paths.
Pattern: /https?:\/\/([\w-]+\.)+[\w-]+(\/[\w\-\.~:\/\?#\[\]@!$&'()*+,;=]*)?/
const urlRegex = /https?:\/\/([\w-]+\.)+[\w-]+(\/[\w\-\.~:\/\?#\[\]@!$&'()*+,;=]*)?/g;
const text = 'Visit https://example.com/page?q=search for more info.';
console.log(text.match(urlRegex));
// ['https://example.com/page?q=search']
3. Date Format Validation (YYYY-MM-DD)
Validates dates in ISO 8601 format.
Pattern: /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/
const dateRegex = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
console.log(dateRegex.test('2026-05-26')); // true
console.log(dateRegex.test('2026-13-01')); // false (invalid month)
Note: This validates format and range but does not check calendar validity (e.g., February 30 passes pattern validation but is not a real date).
4. US Phone Number Validation
Matches common US phone number formats: (555) 123-4567, 555-123-4567, +1 555 123 4567.
Pattern: /^\+?1?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/
const phoneRegex = /^\+?1?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;
console.log(phoneRegex.test('(555) 123-4567')); // true
console.log(phoneRegex.test('555-123-4567')); // true
console.log(phoneRegex.test('12345')); // false
5. IP Address (IPv4)
Validates an IPv4 address with four octets (0–255).
Pattern: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/
const ipRegex = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
console.log(ipRegex.test('192.168.1.1')); // true
console.log(ipRegex.test('256.0.0.1')); // false
Each octet is constrained to 0–255 by using three alternatives: 25[0-5] (250–255), 2[0-4]\d (200–249), and [01]?\d\d? (0–199).
6. HTML Tag Extraction
Extract all HTML tags from a block of markup.
Pattern: /<\/?[\w\s="/.':;#-\/\?]+>/
const htmlRegex = /<\/?[\w\s="'.'":;#-\/\?]+>/g;
const html = '<div class="container"><p>Hello</p></div>';
console.log(html.match(htmlRegex));
// ['<div class="container">', '<p>', '</p>', '</div>']
7. Password Strength Validation
Require at least 8 characters, one uppercase letter, one lowercase letter, one digit, and one special character.
Pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#])[A-Za-z\d@$!%*?&#]{8,}$/
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#])[A-Za-z\d@$!%*?&#]{8,}$/;
console.log(passwordRegex.test('Pass1234!')); // true
console.log(passwordRegex.test('weakpassword')); // false
The (?=.*[a-z]) syntax uses lookahead assertions to check for each character class without consuming characters.
8. Extracting All URLs from Text
Find every URL in a block of text, including those without protocol.
const urlExtractRegex = /https?:\/\/[^\s]+|www\.[^\s]+/g;
const text = 'Check www.example.com and https://google.com for details.';
console.log(text.match(urlExtractRegex));
// ['www.example.com', 'https://google.com']
9. Hex Color Code Validation
Match 3-digit and 6-digit hex color codes, with or without the # prefix.
Pattern: /^#?([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$/
const hexRegex = /^#?([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$/;
console.log(hexRegex.test('#FF5733')); // true
console.log(hexRegex.test('abc')); // true
console.log(hexRegex.test('#GGG')); // false
10. Extracting Numbers from a String
Pull all numeric values out of mixed text.
Pattern: /\d+(\.\d+)?/g
const numRegex = /\d+(\.\d+)?/g;
console.log('Price: $29.99, Qty: 3'.match(numRegex));
// ['29.99', '3']
import re
text = "Price: $29.99, Qty: 3"
print(re.findall(r'\d+(?:\.\d+)?', text))
# ['29.99', '3']
11. Slug Generation (URL-Safe Strings)
Convert any text to a URL-friendly slug.
function slugify(text) {
return text
.toLowerCase()
.replace(/[^\w\s-]/g, '') // remove special chars
.replace(/[\s_]+/g, '-') // spaces/underscores to hyphens
.replace(/^-+|-+$/g, ''); // trim hyphens
}
console.log(slugify('Hello World! How Are You?'));
// 'hello-world-how-are-you'
12. Credit Card Number Validation
Detect common credit card number formats, with optional spaces or hyphens.
Pattern: /^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$/
const ccRegex = /^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}$/;
console.log(ccRegex.test('4111-1111-1111-1111')); // true
console.log(ccRegex.test('4111111111111111')); // true
Security note: Never trust client-side validation alone for payment processing.
13. Time Format (HH:MM AM/PM)
Match 12-hour time format with optional leading zero.
Pattern: /^(0?[1-9]|1[0-2]):[0-5]\d\s?(AM|PM)$/i
const timeRegex = /^(0?[1-9]|1[0-2]):[0-5]\d\s?(AM|PM)$/i;
console.log(timeRegex.test('2:30 PM')); // true
console.log(timeRegex.test('13:00 AM')); // false
14. Username Validation
Validate usernames: 3–16 characters, alphanumeric with underscores and hyphens.
Pattern: /^[a-zA-Z0-9_-]{3,16}$/
const userRegex = /^[a-zA-Z0-9_-]{3,16}$/;
console.log(userRegex.test('john_doe')); // true
console.log(userRegex.test('ab')); // false (too short)
console.log(userRegex.test('user@name')); // false
15. Whitespace Trimming
Remove leading and trailing whitespace from a string.
Pattern: /^\s+|\s+$/g
const text = ' hello world ';
console.log(text.replace(/^\s+|\s+$/g, ''));
// 'hello world'
16. MAC Address Validation
Validate MAC addresses in common formats (AA:BB:CC:DD:EE:FF or AA-BB-CC-DD-EE-FF).
Pattern: /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/
const macRegex = /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/;
console.log(macRegex.test('00:1A:2B:3C:4D:5E')); // true
console.log(macRegex.test('00:1A:2B:3C:4D')); // false
17. Matching Repeated Words
Find duplicate consecutive words (common typo in text).
Pattern: /\b(\w+)\s+\1\b/gi
const dupRegex = /\b(\w+)\s+\1\b/gi;
console.log('This this is a test test.'.match(dupRegex));
// ['This this', 'test test']
18. JSON String Extraction
Extract a JSON object from a larger text body.
Pattern: /\{[\s\S]*\}/
const jsonRegex = /\{[\s\S]*\}/;
const text = 'Response: {"name": "John", "age": 30}';
const match = text.match(jsonRegex);
console.log(match ? JSON.parse(match[0]) : null);
// { name: 'John', age: 30 }
19. File Extension Extraction
Get the file extension from a filename or path.
Pattern: /\.([\w]+)$/
const extRegex = /\.([\w]+)$/;
console.log('document.pdf'.match(extRegex)?.[1]); // 'pdf'
console.log('archive.tar.gz'.match(extRegex)?.[1]); // 'gz'
20. Social Security Number (SSN) Validation
Match the US SSN format (XXX-XX-XXXX) with valid range constraints.
Pattern: /^(?!000|666|9\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$/
const ssnRegex = /^(?!000|666|9\d{2})\d{3}-(?!00)\d{2}-(?!0000)\d{4}$/;
console.log(ssnRegex.test('123-45-6789')); // true
console.log(ssnRegex.test('000-45-6789')); // false (area 000 invalid)
Performance Tips
- Use
RegExp.prototype.test()for boolean checks instead ofString.prototype.match()— it is faster because it stops at the first match. - Avoid catastrophic backtracking by replacing nested quantifiers like
([^,]+,)+with atomic groups or possessive quantifiers where supported. - Compile regex once and reuse — do not create the same regex inside a loop.
- Use raw strings in Python (the
rprefix) to avoid escaping backslashes.
Common Pitfalls
| Mistake | Wrong | Correct |
|---|---|---|
| Unescaped dot | .*\.com | .*\\.com |
| Greedy matching | ".*" | ".*?" |
| Missing anchors | /[a-z]+/ | /^[a-z]+$/ |
| Not escaping in string | new RegExp('\d') | new RegExp('\\d') |
Test Your Patterns
Use our free Regex Tester to experiment with these patterns interactively.