Common Regex Patterns: 20+ Examples for Everyday Development

Most developers copy regex from Stack Overflow without understanding what they’re copying. You paste a pattern, it works, and you move on. But when it breaks or needs tweaking, you’re stuck. This post gives you 20+ battle-tested regex patterns you’ll actually use — and the knowledge to modify them when needed.

Validation Patterns

Email Address

Pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/

Matches basic email format: non-whitespace characters, @ symbol, domain, and top-level domain.

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailPattern.test("user@example.com"));     // true
console.log(emailPattern.test("john.doe@company.co.uk")); // true
console.log(emailPattern.test("invalid.email"));        // false
console.log(emailPattern.test("user@"));                // false

Not RFC-5321 compliant, but sufficient for most web forms. For stricter validation, use a dedicated email library.

URL (HTTP/HTTPS)

Pattern: /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/

Captures http and https URLs with optional www prefix and query parameters.

const urlPattern = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
console.log(urlPattern.test("https://www.example.com"));     // true
console.log(urlPattern.test("http://example.com/path?id=1")); // true
console.log(urlPattern.test("ftp://example.com"));           // false (ftp not allowed)

IPv4 Address

Pattern: /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/

Validates IPv4 addresses with proper octet ranges (0–255).

const ipPattern = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
console.log(ipPattern.test("192.168.1.1"));   // true
console.log(ipPattern.test("255.255.255.255")); // true
console.log(ipPattern.test("256.1.1.1"));     // false (256 exceeds 255)
console.log(ipPattern.test("192.168.1"));     // false (incomplete)

Phone Number (US Format)

Pattern: /^(\+?1?[-.\s]?)?\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})$/

Accepts (555) 123-4567, 555-123-4567, 5551234567, +1-555-123-4567, and variations.

const phonePattern = /^(\+?1?[-.\s]?)?\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})$/;
console.log(phonePattern.test("(555) 123-4567")); // true
console.log(phonePattern.test("555-123-4567"));  // true
console.log(phonePattern.test("5551234567"));    // true
console.log(phonePattern.test("+1-555-123-4567")); // true
console.log(phonePattern.test("555-1234"));     // false (missing digits)

Credit Card Number

Pattern: /^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{3,4}$/

Matches 16-digit credit card numbers with optional spaces or dashes. Does not validate checksums (use Luhn algorithm for that).

const cardPattern = /^\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{3,4}$/;
console.log(cardPattern.test("1234-5678-9012-3456")); // true
console.log(cardPattern.test("1234 5678 9012 3456")); // true
console.log(cardPattern.test("1234567890123456"));    // true
console.log(cardPattern.test("1234-5678-9012"));     // false (too short)

Date (YYYY-MM-DD)

Pattern: /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/

Validates ISO 8601 dates with proper month (01–12) and day (01–31) ranges.

const datePattern = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/;
console.log(datePattern.test("2026-03-29")); // true
console.log(datePattern.test("2026-12-31")); // true
console.log(datePattern.test("2026-13-01")); // false (month 13)
console.log(datePattern.test("2026-03-32")); // false (day 32)

Password Strength

Pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/

Requires at least 8 characters with lowercase, uppercase, digit, and special character. Uses lookaheads to check all conditions.

const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
console.log(passwordPattern.test("Weak123")); // false (no special char)
console.log(passwordPattern.test("Strong@123")); // true
console.log(passwordPattern.test("CAPS@1234")); // false (no lowercase)
console.log(passwordPattern.test("weak@1234")); // false (no uppercase)

Data Extraction Patterns

Extract Domain from URL

Pattern: /^https?:\/\/(www\.)?([^\/?#]+)/

Captures the domain name from a full URL (group 2).

const url = "https://www.example.com/path?id=1";
const match = url.match(/^https?:\/\/(www\.)?([^\/?#]+)/);
console.log(match[2]); // "example.com"

const urls = [
  "https://github.com/user/repo",
  "http://stackoverflow.com/questions/12345",
  "https://www.google.com"
];
urls.forEach(u => {
  const m = u.match(/^https?:\/\/(www\.)?([^\/?#]+)/);
  console.log(m[2]); // "github.com", "stackoverflow.com", "google.com"
});

Extract Prices

Pattern: /\$(\d+(?:\.\d{2})?)/g

Captures dollar amounts (with optional cents) from text.

const text = "Item 1: $19.99, Item 2: $5, Item 3: $100.50";
const prices = [];
const pricePattern = /\$(\d+(?:\.\d{2})?)/g;
let match;
while ((match = pricePattern.exec(text)) !== null) {
  prices.push(match[1]);
}
console.log(prices); // ["19.99", "5", "100.50"]

Extract HTML/XML Tags

Pattern: /<([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>/

Captures opening tag names without closing tags.

const html = "<div class='container'><p>Hello</p></div>";
const tagPattern = /<([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>/g;
const tags = [];
let match;
while ((match = tagPattern.exec(html)) !== null) {
  tags.push(match[1]);
}
console.log(tags); // ["div", "p", "div"]

Extract Words (Alphanumeric)

Pattern: /\b\w+\b/g

Matches whole words (alphanumeric and underscores).

const text = "Hello world! This is a test_123 with symbols.";
const words = text.match(/\b\w+\b/g);
console.log(words); // ["Hello", "world", "This", "is", "a", "test_123", "with", "symbols"]

Extract Email Addresses

Pattern: /\b[^\s@]+@[^\s@]+\.[^\s@]+\b/g

Finds all email addresses in a block of text.

const text = "Contact support@example.com or sales@company.org for help";
const emailPattern = /\b[^\s@]+@[^\s@]+\.[^\s@]+\b/g;
const emails = text.match(emailPattern);
console.log(emails); // ["support@example.com", "sales@company.org"]

Text Processing Patterns

Remove Extra Whitespace

Pattern: /\s+/g (replace with single space)

Collapses multiple spaces, tabs, and newlines into a single space.

const messy = "Hello    world\n\n  how  are   you?";
const clean = messy.replace(/\s+/g, " ");
console.log(clean); // "Hello world how are you?"

Trim Whitespace (Start and End)

Pattern: /^\s+|\s+$/g (replace with empty string)

Removes leading and trailing whitespace.

const padded = "   Hello World   ";
const trimmed = padded.replace(/^\s+|\s+$/g, "");
console.log(trimmed); // "Hello World"

Count Words

Pattern: /\b\w+\b/g

Split text into words using word boundary.

const text = "The quick brown fox jumps over the lazy dog";
const wordCount = (text.match(/\b\w+\b/g) || []).length;
console.log(wordCount); // 8

Convert camelCase to kebab-case

Pattern: /([a-z])([A-Z])/g$1-$2, then lowercase

Inserts hyphens before uppercase letters and converts to lowercase.

const camelCase = "myVariableName";
const kebabCase = camelCase.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
console.log(kebabCase); // "my-variable-name"

Highlight/Wrap Matches

Pattern: /\bword\b/gi (case-insensitive whole word)

Replace matches with wrapped versions (e.g., for highlighting).

const text = "Word is a word. WORD matters.";
const highlighted = text.replace(/\bword\b/gi, "<mark>$&</mark>");
console.log(highlighted); // "Word is a <mark>word</mark>. <mark>WORD</mark> matters."

Security Patterns (Detection Only)

Detect Potential SQL Injection Attempt

Pattern: /(\b(union|select|insert|update|delete|drop|create|alter)\b)|(-{2}|;|\/\*|[\'\"])/gi

Flags SQL keywords and dangerous syntax. Use this for logging/alerts, not for actual sanitization (use parameterized queries instead).

const inputPattern = /(\b(union|select|insert|update|delete|drop|create|alter)\b)|(-{2}|;|\/\*|[\'\"])/gi;
const userInput1 = "search books";
const userInput2 = "'; DROP TABLE users--";

console.log(inputPattern.test(userInput1)); // false (safe)
inputPattern.lastIndex = 0; // reset for reuse
console.log(inputPattern.test(userInput2)); // true (suspicious)

Detect Potential XSS Attempt

Pattern: /<script[^>]*>[\s\S]*?<\/script>/gi (inline scripts)

Also check for event handlers: /\bon\w+\s*=/gi

const xssPattern = /<script[^>]*>[\s\S]*?<\/script>/gi;
const xssInput1 = "Please read my story";
const xssInput2 = "<script>alert('xss')</script>";

console.log(xssPattern.test(xssInput1)); // false (safe)
xssPattern.lastIndex = 0;
console.log(xssPattern.test(xssInput2)); // true (suspicious)

Language-Specific Tips

JavaScript vs Python Differences

FeatureJavaScriptPythonNote
Flags/pattern/flagsre.flag | re.flagJS uses /g, /i, etc. Python uses re.GLOBAL, re.IGNORECASE
Named groups(?<name>...)(?P<name>...)Different syntax
Multiline mode/.../mre.MULTILINEChanges ^ and $ behavior
Methodstest(), match(), replace()search(), findall(), sub()Different method names
Backreferences\1, \2\1, \2 (in pattern) or \g<1> (in replacement)Same in patterns, different in Python replacements

JavaScript Example

const text = "apple123banana456";
const pattern = /(\w+)(\d+)/g;
const matches = [];
let match;
while ((match = pattern.exec(text)) !== null) {
  matches.push({ word: match[1], number: match[2] });
}
console.log(matches);
// [{ word: "apple", number: "123" }, { word: "banana", number: "456" }]

Python Example

import re

text = "apple123banana456"
pattern = r'(\w+)(\d+)'
matches = re.findall(pattern, text)
print(matches)
# [('apple', '123'), ('banana', '456')]

# Replacement with backreferences
result = re.sub(r'(\w+)(\d+)', r'\2-\1', text)
print(result)  # "123-apple456-banana"

Common Mistakes to Avoid

1. Forgetting the Global Flag

Without g, you get only the first match. This is a source of countless bugs.

const text = "cat cat cat";
console.log(text.match(/cat/));   // ["cat"] ← first only
console.log(text.match(/cat/g));  // ["cat", "cat", "cat"] ← all matches

2. Using Greedy When You Need Lazy

The default *, +, and {} are greedy. Add ? to make them lazy.

const html = "<div>hello</div><div>world</div>";
console.log(html.match(/<div>.*<\/div>/)[0]);
// "<div>hello</div><div>world</div>" ← greedy (wrong)

console.log(html.match(/<div>.*?<\/div>/g));
// ["<div>hello</div>", "<div>world</div>"] ← lazy (correct)

3. Forgetting to Escape Special Characters

Special characters (., *, +, ?, ^, $, [, ], {, }, (, ), \, |) have special meaning. Escape them with \ to match literally.

const price = "1.00";
console.log(/1.00/.test(price));   // true (but matches "1a00", "1x00", etc.)
console.log(/1\.00/.test(price));  // true (matches "1.00" only)

4. Assuming . Matches Newlines

By default, . matches any character except newline. Use the s flag (dotall) to change this.

const multiline = "line1\nline2";
console.log(/line1.line2/.test(multiline));   // false
console.log(/line1.line2/s.test(multiline));  // true (with s flag)

5. Not Resetting Global Regex State

If you reuse a global regex (with flag g), the lastIndex persists. Call reset() or reassign the regex.

const pattern = /\d+/g;
console.log(pattern.test("123 abc"));    // true, lastIndex = 3
console.log(pattern.test("456 def"));    // false! (starts at index 3)

// Fix: either reassign or reset lastIndex
pattern.lastIndex = 0;
console.log(pattern.test("456 def"));    // true

Frequently Asked Questions

What is the simplest email validation regex?

/^[^\s@]+@[^\s@]+\.[^\s@]+$/ is practical but not RFC-compliant. For production, use a dedicated email validation library or send a confirmation email. Regex alone cannot check if an email account actually exists.

How do I match a literal period or asterisk?

Escape them with a backslash: /1\.00/ matches “1.00” (literal period). /\*/ matches an asterisk. Learn which characters need escaping: ., *, +, ?, ^, $, [, ], {, }, (, ), \, |.

What’s the difference between \d and [0-9]?

Both match digits. \d is shorter and includes Unicode digits in some engines. [0-9] is explicit and faster in most regex engines. For ASCII-only matching, [0-9] is preferred.

How do I extract multiple matches into an array?

Use .match(/pattern/g) in JavaScript or re.findall() in Python. For groups, use matchAll() (JS) or finditer() (Python). See the data extraction section for examples.

Can regex validate dates correctly?

Regex can check format, but not logic (e.g., February 30). Use regex for format, then parse with a date library like Date.parse() or datetime.strptime() to validate the actual date.

What is catastrophic backtracking?

Patterns like (a+)+b force the regex engine to try exponential combinations on non-matching input, causing hangs. Avoid nested quantifiers. Use possessive quantifiers (?>a+) or atomic groups (?>...) if your engine supports them.

Conclusion

These 20+ patterns cover most everyday development tasks: validation, extraction, text processing, and security detection. Instead of copying blindly from Stack Overflow, you now understand why each pattern works.

Test all these patterns live in our Regex Tester — type your pattern and test string, get instant visual feedback, and debug before deploying. Start simple, test thoroughly, and build your regex confidence one pattern at a time. See also: Regex Cheat Sheet for deeper syntax reference.

Related Tools