5 Regex Patterns Every Developer Should Know
Regular expressions are one of those tools that can feel intimidating at first, but once you understand them, they become indispensable. Whether you're validating user input, parsing logs, or searching through code, regex patterns will save you hours of work.
The problem is that most developers either avoid regex entirely or copy patterns from Stack Overflow without understanding them. This leads to bugs, security vulnerabilities, and maintenance headaches.
Let's fix that. Here are five essential regex patterns every developer should understand—not just copy.
1. Email Validation
Email validation is one of the most common uses for regex. While a truly RFC-compliant email regex is absurdly complex, a practical pattern handles 99% of real-world cases.
The Pattern
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Breaking It Down
| Part | Meaning |
|---|---|
^ | Start of string |
[a-zA-Z0-9._%+-]+ | One or more valid username characters |
@ | Literal @ symbol |
[a-zA-Z0-9.-]+ | One or more valid domain characters |
\. | Literal dot (escaped) |
[a-zA-Z]{2,} | TLD with at least 2 letters |
$ | End of string |
Example Usage (JavaScript)
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
// Valid emails
emailRegex.test('user@example.com'); // true
emailRegex.test('john.doe@company.co.uk'); // true
emailRegex.test('admin+filter@mail.io'); // true
// Invalid emails
emailRegex.test('invalid'); // false
emailRegex.test('@nodomain.com'); // false
emailRegex.test('missing@tld.'); // false
Important Caveat
This pattern doesn't guarantee the email exists or can receive mail—it only validates the format. For critical applications, always combine regex validation with email verification (sending a confirmation link).
2. URL Matching
URLs come in many forms: with or without protocols, with ports, query strings, and fragments. A good URL pattern needs to handle this variety.
The Pattern
^(https?:\/\/)?([\w.-]+)\.([a-z]{2,})(:\d+)?(\/[^\s]*)?$
Breaking It Down
| Part | Meaning |
|---|---|
^ | Start of string |
(https?:\/\/)? | Optional http:// or https:// |
([\w.-]+) | Domain name (letters, numbers, dots, hyphens) |
\.([a-z]{2,}) | TLD with at least 2 letters |
(:\d+)? | Optional port number |
(\/[^\s]*)? | Optional path (anything after /) |
$ | End of string |
Example Usage (JavaScript)
const urlRegex = /^(https?:\/\/)?([\w.-]+)\.([a-z]{2,})(:\d+)?(\/[^\s]*)?$/i;
// Valid URLs
urlRegex.test('https://example.com'); // true
urlRegex.test('http://api.example.com:8080'); // true
urlRegex.test('example.com/path/to/page'); // true
urlRegex.test('sub.domain.example.org/page?q=1'); // true
// Invalid URLs
urlRegex.test('not a url'); // false
urlRegex.test('ftp://wrong-protocol.com'); // false
When to Use This
URL validation with regex is great for quick format checks. For parsing URLs into components (protocol, host, path, query), use your language's built-in URL parser instead—it handles edge cases better.
3. Phone Number Formats
Phone numbers vary wildly across countries. This pattern handles common North American and international formats.
The Pattern
^[\+]?[(]?[0-9]{1,3}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{1,4}[-\s\.]?[0-9]{1,9}$
A Cleaner Alternative
For better readability, break down what you're matching:
^\+?1?[-.\s]?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}$
This specifically matches US/Canada format: +1 (555) 123-4567
Breaking It Down
| Part | Meaning |
|---|---|
^\+?1? | Optional + and country code 1 |
[-.\s]? | Optional separator (dash, dot, or space) |
\(?[0-9]{3}\)? | Area code with optional parentheses |
[-.\s]? | Optional separator |
[0-9]{3} | First 3 digits |
[-.\s]? | Optional separator |
[0-9]{4}$ | Last 4 digits |
Example Usage (JavaScript)
const phoneRegex = /^\+?1?[-.\s]?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}$/;
// Valid formats
phoneRegex.test('555-123-4567'); // true
phoneRegex.test('(555) 123-4567'); // true
phoneRegex.test('+1 555 123 4567'); // true
phoneRegex.test('5551234567'); // true
// Invalid formats
phoneRegex.test('123-456'); // false (too short)
phoneRegex.test('abc-def-ghij'); // false (letters)
Pro Tip
For international applications, consider using a library like libphonenumber (available in most languages). It handles country-specific validation, formatting, and parsing far better than any single regex can.
4. Password Strength Validation
Password validation often needs to enforce multiple rules: minimum length, uppercase, lowercase, numbers, and special characters. Regex with lookaheads makes this elegant.
The Pattern
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Breaking It Down
| Part | Meaning |
|---|---|
^ | Start of string |
(?=.*[a-z]) | Lookahead: must contain lowercase |
(?=.*[A-Z]) | Lookahead: must contain uppercase |
(?=.*\d) | Lookahead: must contain digit |
(?=.*[@$!%*?&]) | Lookahead: must contain special char |
[A-Za-z\d@$!%*?&]{8,} | At least 8 allowed characters |
$ | End of string |
Understanding Lookaheads
Lookaheads (?=...) check for a condition without consuming characters. They're like asking "is this ahead?" without moving forward. This lets us check multiple conditions on the same string.
Example Usage (JavaScript)
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
// Strong passwords
passwordRegex.test('MyP@ssw0rd'); // true
passwordRegex.test('Secure123!'); // true
// Weak passwords
passwordRegex.test('password'); // false (no uppercase, digit, special)
passwordRegex.test('PASSWORD1!'); // false (no lowercase)
passwordRegex.test('Pass1!'); // false (too short)
Giving Better Feedback
Instead of one monolithic regex, consider checking each rule separately:
function validatePassword(password) {
const rules = [
{ test: /.{8,}/, message: 'At least 8 characters' },
{ test: /[a-z]/, message: 'At least one lowercase letter' },
{ test: /[A-Z]/, message: 'At least one uppercase letter' },
{ test: /\d/, message: 'At least one number' },
{ test: /[@$!%*?&]/, message: 'At least one special character' },
];
return rules
.filter(rule => !rule.test.test(password))
.map(rule => rule.message);
}
validatePassword('weak');
// ['At least 8 characters', 'At least one uppercase letter',
// 'At least one number', 'At least one special character']
This approach gives users actionable feedback instead of just "invalid password."
5. Extracting Data from Logs
Log parsing is where regex truly shines. Server logs follow predictable patterns, making them perfect for regex extraction.
Common Log Format Pattern
^(\S+) (\S+) (\S+) \[([^\]]+)\] "(\S+) (\S+) (\S+)" (\d{3}) (\d+|-)
This matches Apache Common Log Format:
127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326
Breaking It Down
| Group | Part | Captures |
|---|---|---|
| 1 | (\S+) | IP address |
| 2 | (\S+) | Identity (usually -) |
| 3 | (\S+) | User ID |
| 4 | \[([^\]]+)\] | Timestamp |
| 5 | (\S+) | HTTP method |
| 6 | (\S+) | Requested path |
| 7 | (\S+) | Protocol |
| 8 | (\d{3}) | Status code |
| 9 | (\d+|-) | Response size |
Example Usage (JavaScript)
const logRegex = /^(\S+) (\S+) (\S+) \[([^\]]+)\] "(\S+) (\S+) (\S+)" (\d{3}) (\d+|-)/;
const logLine = '192.168.1.1 - john [15/Jan/2026:10:30:00 +0000] "GET /api/users HTTP/1.1" 200 1234';
const match = logLine.match(logRegex);
if (match) {
console.log({
ip: match[1], // '192.168.1.1'
user: match[3], // 'john'
timestamp: match[4], // '15/Jan/2026:10:30:00 +0000'
method: match[5], // 'GET'
path: match[6], // '/api/users'
status: match[8], // '200'
size: match[9] // '1234'
});
}
Extracting Error Messages
A simpler pattern for finding errors:
\b(ERROR|WARN|FATAL)\b.*?:\s*(.+)$
const errorRegex = /\b(ERROR|WARN|FATAL)\b.*?:\s*(.+)$/gm;
const logs = `
2026-01-15 10:30:00 INFO Starting server
2026-01-15 10:30:01 ERROR Database connection: Connection refused
2026-01-15 10:30:02 WARN Memory usage: 85% threshold exceeded
`;
let match;
while ((match = errorRegex.exec(logs)) !== null) {
console.log(`${match[1]}: ${match[2]}`);
}
// ERROR: Connection refused
// WARN: 85% threshold exceeded
Named Capture Groups (Modern JavaScript)
Modern JavaScript supports named capture groups for more readable code:
const logRegex = /^(?<ip>\S+) \S+ (?<user>\S+) \[(?<time>[^\]]+)\] "(?<method>\S+) (?<path>\S+)/;
const match = logLine.match(logRegex);
console.log(match.groups.ip); // '192.168.1.1'
console.log(match.groups.path); // '/api/users'
Quick Reference Cheat Sheet
Here's a handy reference for the patterns covered:
| Use Case | Pattern |
|---|---|
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ | |
| URL | ^(https?:\/\/)?([\w.-]+)\.([a-z]{2,})(:\d+)?(\/[^\s]*)?$ |
| US Phone | ^\+?1?[-.\s]?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}$ |
| Strong Password | ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$ |
| Log Errors | \b(ERROR|WARN|FATAL)\b.*?:\s*(.+)$ |
Common Regex Symbols
| Symbol | Meaning | Example |
|---|---|---|
. | Any character except newline | a.c matches "abc", "a1c" |
* | Zero or more | ab*c matches "ac", "abc", "abbc" |
+ | One or more | ab+c matches "abc", "abbc" but not "ac" |
? | Zero or one | colou?r matches "color", "colour" |
^ | Start of string | ^Hello matches "Hello world" |
$ | End of string | world$ matches "Hello world" |
\d | Any digit | \d{3} matches "123" |
\w | Word character | \w+ matches "hello_123" |
\s | Whitespace | \s+ matches spaces, tabs, newlines |
[abc] | Character set | [aeiou] matches any vowel |
[^abc] | Negated set | [^0-9] matches non-digits |
(...) | Capture group | (ab)+ captures repeated "ab" |
(?=...) | Positive lookahead | a(?=b) matches "a" followed by "b" |
| | Alternation (OR) | cat|dog matches "cat" or "dog" |
Continue Learning
These five patterns cover the most common regex use cases, but there's much more to explore: backreferences, lookbehinds, non-greedy matching, and Unicode support.
-
Want hands-on practice? Our Interactive Regex Practice course lets you build patterns step by step with instant visual feedback. Start with basics and work up to advanced lookaheads.
-
Building web forms? Check out our JavaScript and React courses to see how these patterns integrate into real validation workflows.
The key to mastering regex isn't memorizing patterns—it's understanding how to break down what you want to match into components. Once you can read regex fluently, you'll find countless opportunities to use it in your daily work.
Start with these five patterns. Understand them. Modify them for your needs. And soon, you'll be writing your own patterns from scratch.

