Regex Cheat Sheet: The Most Useful Regular Expressions (With Examples)
Regular expressions are one of those tools that developers either love or avoid entirely. The syntax looks like line noise at first glance, but once you understand the building blocks, you can validate input, extract data, and perform complex search-and-replace operations in seconds.
This cheat sheet covers the fundamentals first, then gives you 20 practical, copy-paste-ready patterns with detailed breakdowns. Test any pattern live with our Regex Tester.
Regex Fundamentals
Character Classes
| Pattern | Meaning | Example Match |
|---|---|---|
. |
Any character except newline | a.c → "abc", "a1c", "a-c" |
\d |
Any digit [0-9] | \d{3} → "123", "456" |
\D |
Any non-digit | \D+ → "abc", "---" |
\w |
Word character [a-zA-Z0-9_] | \w+ → "hello_world" |
\W |
Non-word character | \W → " ", "@", "!" |
\s |
Whitespace (space, tab, newline) | \s+ → " ", "\t\n" |
[abc] |
Any character in the set | [aeiou] → "a", "e" |
[^abc] |
Any character NOT in the set | [^0-9] → "a", "Z" |
[a-z] |
Character range | [A-Fa-f0-9] → hex chars |
Quantifiers
| Pattern | Meaning | Example |
|---|---|---|
* |
0 or more | ab*c → "ac", "abc", "abbc" |
+ |
1 or more | ab+c → "abc", "abbc" (not "ac") |
? |
0 or 1 (optional) | colou?r → "color", "colour" |
{n} |
Exactly n times | \d{4} → "2025" |
{n,m} |
Between n and m times | \d{2,4} → "12", "123", "1234" |
{n,} |
n or more times | \w{3,} → words with 3+ chars |
*? +? |
Lazy (match as few as possible) | <.+?> → matches one tag, not all |
Anchors and Boundaries
| Pattern | Meaning |
|---|---|
^ |
Start of string (or line with m flag) |
$ |
End of string (or line with m flag) |
\b |
Word boundary (between \w and \W) |
Groups and Lookaround
| Pattern | Meaning |
|---|---|
(abc) |
Capturing group — stores the match |
(?:abc) |
Non-capturing group — groups without storing |
(?<name>abc) |
Named capturing group |
a|b |
Alternation — matches a OR b |
(?=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 |
Common Flags
| Flag | Name | Effect |
|---|---|---|
g |
Global | Find all matches, not just the first |
i |
Case-insensitive | /hello/i matches "Hello", "HELLO" |
m |
Multiline | ^ and $ match line boundaries |
s |
Dotall | . matches newline characters too |
20 Practical Regex Patterns You'll Actually Use
Each pattern below includes the regex, a breakdown of what each part does, and example matches. Copy any pattern and test it in our Regex Tester.
1. Email Address
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
^ Start of string
[a-zA-Z0-9._%+-]+ Local part (letters, digits, dots, underscores, etc.)
@ Literal @ symbol
[a-zA-Z0-9.-]+ Domain name
\. Literal dot
[a-zA-Z]{2,} TLD (at least 2 letters)
$ End of string
✓ user@example.com ✓ first.last+tag@sub.domain.org ✗ @missing.com ✗ user@.com
2. URL (HTTP/HTTPS)
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
https? "http" or "https"
:\/\/ "://"
(www\.)? Optional "www."
[-a-zA-Z0-9...]+ Domain characters
\.[a-zA-Z0-9()]+ TLD
\b Word boundary
([-a-zA-Z0-9...]*) Path, query, and fragment
✓ https://example.com/path?q=1 ✓ http://sub.domain.org ✗ ftp://files.com
3. IPv4 Address
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$
25[0-5] 250-255
2[0-4]\d 200-249
[01]?\d\d? 0-199
\. Dot separator (repeated 3 times)
✓ 192.168.1.1 ✓ 255.255.255.0 ✗ 256.1.1.1 ✗ 192.168.1
4. US Phone Number
^(\+1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
(\+1[-.\s]?)? Optional country code "+1"
\(?\d{3}\)? Area code, optional parentheses
[-.\s]? Optional separator (dash, dot, space)
\d{3} Exchange
\d{4} Subscriber number
✓ (555) 123-4567 ✓ +1-555-123-4567 ✓ 5551234567 ✗ 123-456
5. Date (YYYY-MM-DD)
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
\d{4} Four-digit year
(0[1-9]|1[0-2]) Month 01-12
(0[1-9]|[12]\d|3[01]) Day 01-31
✓ 2026-01-30 ✓ 2000-01-01 ✗ 2025-13-01 ✗ 2025-00-15
6. Hex Color Code
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
# Literal hash
[A-Fa-f0-9]{6} 6 hex digits (#FF00AA)
| OR
[A-Fa-f0-9]{3} 3 hex digits (#F0A shorthand)
✓ #FF5733 ✓ #abc ✗ #GG0000 ✗ FF5733 (missing #)
7. HTML Tag
<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>
<([a-z][a-z0-9]*) Opening tag name (captured as group 1)
\b[^>]*> Attributes and closing >
(.*?) Tag content (lazy match)
<\/\1> Closing tag matching group 1
✓ <p>text</p> ✓ <div class="box">content</div>
Warning: Don't use regex to parse complex HTML. Use a proper HTML parser for production code. Regex is fine for quick searches and simple extractions.
8. File Extension
\.([a-zA-Z0-9]{1,10})$
\. Literal dot
([a-zA-Z0-9]+) Extension (captured)
$ End of string
✓ report.pdf → "pdf" ✓ archive.tar.gz → "gz" ✓ image.JPEG → "JPEG"
9. Strong Password
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
(?=.*[a-z]) At least one lowercase letter
(?=.*[A-Z]) At least one uppercase letter
(?=.*\d) At least one digit
(?=.*[@$!%*?&]) At least one special character
{8,} Minimum 8 characters total
✓ Pa$$w0rd! ✓ MyStr0ng@Pass ✗ password ✗ 12345678
10. UUID v4
^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$
[0-9a-f]{8} 8 hex chars
4[0-9a-f]{3} Version 4 indicator
[89ab][0-9a-f]{3} Variant bits
✓ 550e8400-e29b-41d4-a716-446655440000
11. Positive Integer
^[1-9]\d*$
✓ 1 ✓ 42 ✓ 100000 ✗ 0 ✗ -5 ✗ 3.14
12. Decimal Number (With Optional Negation)
^-?\d+(\.\d+)?$
-? Optional negative sign
\d+ Integer part
(\.\d+)? Optional decimal part
✓ 42 ✓ -3.14 ✓ 0.5 ✗ .5 ✗ 3.
13. Slug (URL-Friendly String)
^[a-z0-9]+(-[a-z0-9]+)*$
✓ my-blog-post ✓ regex101 ✗ My Blog Post ✗ --double-dash
14. Username (Alphanumeric, 3-16 Characters)
^[a-zA-Z][a-zA-Z0-9_]{2,15}$
[a-zA-Z] Must start with a letter
[a-zA-Z0-9_]{2,15} 2-15 more alphanumeric or underscore chars
✓ alice_42 ✓ Bob ✗ 1user ✗ ab ✗ this_is_way_too_long_username
15. Credit Card Number (Basic)
^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12})$
4[0-9]{12,15} Visa (starts with 4)
5[1-5][0-9]{14} Mastercard (51-55)
3[47][0-9]{13} Amex (34 or 37)
6011|65[0-9]{14} Discover
✓ 4111111111111111 (Visa test) ✓ 5500000000000004 (MC test)
16. Time (24-Hour Format)
^([01]\d|2[0-3]):([0-5]\d)$
[01]\d|2[0-3] Hours 00-23
[0-5]\d Minutes 00-59
✓ 09:30 ✓ 23:59 ✗ 24:00 ✗ 9:5
17. MAC Address
^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$
✓ 00:1A:2B:3C:4D:5E ✓ 00-1A-2B-3C-4D-5E ✗ 00:1A:2B:3C:4D
18. ZIP Code (US 5-Digit or 5+4)
^\d{5}(-\d{4})?$
✓ 90210 ✓ 90210-1234 ✗ 9021 ✗ 902101234
19. Whitespace Trimmer (for Search-and-Replace)
^\s+|\s+$
^\s+ Leading whitespace
| OR
\s+$ Trailing whitespace
Use with replace("") to trim strings:
" hello ".replace(/^\s+|\s+$/g, "") → "hello"
20. Duplicate Words
\b(\w+)\s+\1\b
(\w+) Capture a word
\s+ Followed by whitespace
\1 Followed by the same word (backreference)
✓ "the the" ✓ "is is" ✗ "the then"
Tips for Writing Better Regex
- Be specific. Use
[a-zA-Z]instead of.when you know you want letters. Overly broad patterns match things you don't intend. - Anchor your patterns. Use
^and$when validating entire strings. Without anchors,\d{3}will match inside "abc123def". - Prefer lazy quantifiers for extraction. Use
.*?instead of.*when you want the shortest match (e.g., extracting content between tags). - Use named groups for readability.
(?<year>\d{4})-(?<month>\d{2})is clearer than(\d{4})-(\d{2})when you're extracting data. - Test with edge cases. Always test with empty strings, very long strings, and inputs containing special characters.
- Watch for catastrophic backtracking. Patterns like
(a+)+$can hang your program on certain inputs. Avoid nested quantifiers when possible.
Frequently Asked Questions
What's the difference between .* and .*? (greedy vs lazy)?
.* is greedy — it matches as many characters as possible. .*? is lazy — it matches as few characters as possible. For example, given the string <b>hello</b> world <b>foo</b>, the pattern <b>.*</b> matches everything from the first <b> to the last </b>. The lazy version <b>.*?</b> matches just <b>hello</b>. Use lazy quantifiers when extracting individual occurrences.
Should I use regex to validate email addresses?
A simple regex like the one in pattern #1 above catches the vast majority of invalid inputs and is fine for client-side form validation. However, the full email spec (RFC 5322) is extremely complex and essentially impossible to capture perfectly in a single regex. For production systems, validate the format with a simple regex, then confirm the email actually exists by sending a verification message.
Why does my regex work in JavaScript but not Python?
Different regex engines have slightly different feature sets. JavaScript uses the /pattern/flags syntax, while Python uses raw strings r"pattern". Some features like lookbehind with variable length are supported in Python but not in all JavaScript engines. Named groups use (?P<name>...) in Python but (?<name>...) in JavaScript. Always test in the target language or use our Regex Tester to verify.
What is catastrophic backtracking and how do I avoid it?
Catastrophic backtracking occurs when a regex engine explores an exponential number of paths trying to match a pattern. It typically happens with nested quantifiers like (a+)+ or overlapping alternations. On a non-matching input, the engine can take minutes or hang indefinitely. Avoid it by keeping patterns simple, avoiding nested repetition, and using atomic groups or possessive quantifiers where available. If your regex runs slowly on valid inputs, it's a sign of backtracking problems.