Regex Cheat Sheet: Complete Regular Expression Guide
Master regular expressions with this comprehensive cheat sheet and practical examples.
Regular expressions (regex) are powerful tools for pattern matching in strings. While they can seem intimidating at first, once you understand the basics, they become invaluable for text processing, validation, and data extraction.
Basic Syntax
| Pattern | Description | Example |
|---|---|---|
| . | Any character except newline | a.c matches "abc", "a1c" |
| ^ | Start of string | ^Hello matches "Hello world" |
| $ | End of string | world$ matches "Hello world" |
| \d | Any digit (0-9) | \d+ matches "123" |
| \w | Word character (a-z, A-Z, 0-9, _) | \w+ matches "hello_123" |
| \s | Whitespace (space, tab, newline) | \s+ matches spaces |
Quantifiers
| Pattern | Description | Example |
|---|---|---|
| * | 0 or more | ab*c matches "ac", "abc", "abbc" |
| + | 1 or more | ab+c matches "abc", "abbc" |
| ? | 0 or 1 | colou?r matches "color", "colour" |
| {n} | Exactly n times | \d{3} matches "123" |
| {n,} | n or more times | \d{2,} matches "12", "123" |
| {n,m} | Between n and m times | \d{2,4} matches "12", "1234" |
Character Classes
| Pattern | Description | Example |
|---|---|---|
| [abc] | Any of a, b, or c | [aeiou] matches vowels |
| [^abc] | Not a, b, or c | [^0-9] matches non-digits |
| [a-z] | Range: a to z | [A-Za-z] matches letters |
| \D | Non-digit | \D+ matches "abc" |
| \W | Non-word character | \W matches "@", "#" |
| \S | Non-whitespace | \S+ matches words |
Groups and Lookahead
| Pattern | Description |
|---|---|
| (abc) | Capturing group |
| (?:abc) | Non-capturing group |
| (?=abc) | Positive lookahead |
| (?!abc) | Negative lookahead |
| (?<=abc) | Positive lookbehind |
| (?<!abc) | Negative lookbehind |
Common Regex Patterns
Email Validation
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
URL Validation
^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$
Phone Number (US)
^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$
Password (Strong)
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
IPv4 Address
^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
Hex Color Code
^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$
Test Your Regex Patterns
Try out these patterns with our free online regex tester.
Try Regex Tester →Regex Tips
- Start simple: Build your regex piece by piece
- Use non-greedy quantifiers: Add
?after*or+for minimal matching - Escape special characters: Use
\before. * + ? ^ $ { } [ ] \ | ( ) - Test incrementally: Test parts of your regex as you build it
- Use comments: In verbose mode, add
# commentsfor clarity
Conclusion
Regular expressions are a powerful tool every developer should know. Bookmark this cheat sheet and practice with our Regex Tester to master pattern matching.