Regex Patterns Cheatsheet: Common Expressions Explained

ยท 8 min read

Regex Basics

Regular expressions (regex) are patterns used to match character combinations in strings. They're powerful for validation, search-and-replace, and data extraction. Every developer encounters regex, whether validating form inputs, parsing log files, or writing URL routing rules.

A regex pattern consists of literal characters and special metacharacters. For example, /hello/ matches the literal text "hello", while /h.llo/ matches "hello", "hallo", "hxllo" โ€” the dot . matches any single character.

Here's a quick reference of the most essential metacharacters:

.     Any character (except newline)
\d    Digit [0-9]
\D    Non-digit
\w    Word character [a-zA-Z0-9_]
\W    Non-word character
\s    Whitespace (space, tab, newline)
\S    Non-whitespace
\b    Word boundary
^     Start of string
$     End of string

๐Ÿ› ๏ธ Test your regex patterns instantly

Regex Tester โ†’ Code Formatter โ†’

Character Classes & Quantifiers

Character classes define sets of characters to match, and quantifiers specify how many times to match:

# Character Classes
[abc]       Match a, b, or c
[^abc]      Match anything except a, b, or c
[a-z]       Match any lowercase letter
[A-Z]       Match any uppercase letter
[0-9]       Match any digit (same as \d)
[a-zA-Z]    Match any letter
[a-zA-Z0-9] Match any alphanumeric character

# Quantifiers
*           Zero or more
+           One or more
?           Zero or one (optional)
{3}         Exactly 3
{3,}        3 or more
{3,6}       Between 3 and 6
*?          Zero or more (lazy/non-greedy)
+?          One or more (lazy/non-greedy)

The difference between greedy and lazy quantifiers is crucial. Greedy (*) matches as much as possible, while lazy (*?) matches as little as possible. For example, given the string <b>bold</b>:

/<.*>/   โ†’ matches "<b>bold</b>" (greedy โ€” entire string)
/<.*?>/  โ†’ matches "<b>" (lazy โ€” first tag only)

Common Regex Patterns

Here are battle-tested patterns for common validation tasks. Test them with our Regex Tester:

Email Validation

# Basic email validation
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

# Examples that match:
# [email protected] โœ“
# [email protected] โœ“
# [email protected] โœ“

URL Matching

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

# Simpler version
^https?:\/\/[^\s/$.?#].[^\s]*$

Phone Numbers

# US phone number (various formats)
^(\+1)?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$

# Matches: +1-555-123-4567, (555) 123-4567, 5551234567

# International (E.164 format)
^\+[1-9]\d{1,14}$

Password Strength

# At least 8 chars, 1 uppercase, 1 lowercase, 1 digit, 1 special char
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

IP Address

# IPv4 address
^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$

# Matches: 192.168.1.1, 10.0.0.1, 255.255.255.0

Use our IP Lookup tool to get details about any IP address you extract with regex.

Date Formats

# YYYY-MM-DD
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$

# MM/DD/YYYY
^(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])\/\d{4}$

# ISO 8601 datetime
^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})?$

Hex Color Codes

# Match hex colors (#fff or #ffffff)
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$

Found a hex color? Check it visually with our Color Picker tool.

Anchors, Groups & Lookaheads

Advanced regex features for more precise matching:

# Groups - Capture matched text
/(\\d{4})-(\\d{2})-(\\d{2})/
# On "2026-03-15": group 1 = "2026", group 2 = "03", group 3 = "15"

# Named groups
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/

# Non-capturing group (doesn't create a capture)
/(?:https?):\/\//

# Alternation (OR)
/cat|dog|bird/

# Lookahead - Match only if followed by pattern
/\d+(?= dollars)/     # Matches "100" in "100 dollars"

# Negative lookahead
/\d+(?! dollars)/     # Matches "100" in "100 euros"

# Lookbehind - Match only if preceded by pattern
/(?<=\$)\d+/          # Matches "50" in "$50"

# Negative lookbehind
/(?<!\$)\d+/          # Matches "50" in "โ‚ฌ50"

Regex in JavaScript

JavaScript has built-in regex support via the RegExp object and string methods:

// Creating regex patterns
const pattern1 = /hello/i;              // Literal (case-insensitive)
const pattern2 = new RegExp('hello', 'i'); // Constructor

// Testing if a string matches
/^\d+$/.test('12345');  // true
/^\d+$/.test('123abc'); // false

// Finding matches
const text = 'Call 555-1234 or 555-5678';
const matches = text.match(/\d{3}-\d{4}/g);
// ["555-1234", "555-5678"]

// Named capture groups
const dateStr = '2026-03-15';
const { groups } = dateStr.match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(groups.year);  // "2026"
console.log(groups.month); // "03"

// Replace with regex
'hello world'.replace(/world/, 'JavaScript');
// "hello JavaScript"

// Replace all occurrences
'aabbcc'.replaceAll(/[bc]/g, 'x');
// "aaxxxx"

// Split with regex
'one, two;  three'.split(/[,;]\s*/);
// ["one", "two", "three"]

Regex in Python

import re

# Match at the beginning of string
result = re.match(r'^\d{3}', '123abc')
print(result.group())  # "123"

# Search anywhere in string
result = re.search(r'\d+', 'abc 456 def')
print(result.group())  # "456"

# Find all matches
emails = re.findall(
    r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
    'Contact [email protected] or [email protected]'
)
# ['[email protected]', '[email protected]']

# Replace
clean = re.sub(r'\s+', ' ', 'too   many    spaces')
# "too many spaces"

# Compile for reuse (better performance)
email_pattern = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
email_pattern.match('[email protected]')  # Match object
email_pattern.match('not-an-email')      # None

Performance Tips

  1. Be specific. Use \d instead of . when you know you want digits. Specific patterns fail faster on non-matching input.
  2. Avoid catastrophic backtracking. Patterns like (a+)+ can cause exponential processing time. Use atomic groups or possessive quantifiers when available.
  3. Use non-capturing groups. If you don't need the captured text, use (?:...) instead of (...) โ€” it's slightly faster.
  4. Anchor your patterns. Using ^ and $ tells the engine exactly where to start and stop matching.
  5. Compile regex patterns when using them repeatedly in loops (in Python, use re.compile()).
  6. Test your patterns with our Regex Tester before deploying โ€” check both matching and non-matching inputs.

Frequently Asked Questions

What does the 'g' flag mean in regex?

The 'g' (global) flag finds all matches in a string, not just the first one. Without it, most regex methods stop after the first match. Other common flags: 'i' for case-insensitive, 'm' for multiline, and 's' for dotAll (makes . match newlines).

How do I match a literal dot or special character?

Escape special characters with a backslash. To match a literal dot, use \. instead of . (which matches any character). Characters that need escaping: ^ $ * + ? { } [ ] ( ) | \

What's the difference between .* and .*? in regex?

.* is greedy โ€” it matches as much text as possible. .*? is lazy (non-greedy) โ€” it matches as little as possible. Use lazy quantifiers when you want the shortest possible match, such as extracting content between HTML tags.

Can regex validate email addresses perfectly?

No regex can perfectly validate all valid email addresses per RFC 5322 (the spec is surprisingly complex). However, a practical pattern handles 99%+ of real-world emails. For thorough validation, combine regex with actually sending a verification email.

Related Tools

Regex Tester Code Formatter Color Picker IP Lookup