·7 min read
Regular Expressions: A Practical Cheat Sheet
Regular expressions (regex) are powerful pattern-matching tools used in nearly every programming language. This cheat sheet covers the most useful patterns you will encounter in day-to-day development.
Basic Syntax
. Any character (except newline) \d Digit (0-9) \w Word character (a-z, A-Z, 0-9, _) \s Whitespace (space, tab, newline) \b Word boundary ^ Start of string $ End of string
Quantifiers
* 0 or more
+ 1 or more
? 0 or 1 (optional)
{n} Exactly n times
{n,m} Between n and m times
{n,} n or more timesCommon Patterns
Email: [\w.-]+@[\w.-]+\.\w+
URL: https?://[^\s]+
Phone: \d{3}[-.]?\d{3}[-.]?\d{4}
IP v4: \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
Date: \d{4}-\d{2}-\d{2}
Hex color: #[0-9a-fA-F]{6}
HTML tag: <([a-z]+)[^>]*>.*?</\1>Character Classes
[abc] a, b, or c [^abc] Not a, b, or c [a-z] a through z [A-Za-z] Any letter [0-9] Any digit
Groups and Capturing
(abc) Capture group (?:abc) Non-capturing group (?=abc) Positive lookahead (?!abc) Negative lookahead a|b a or b (alternation)
Flags
g Global (find all matches) i Case-insensitive m Multiline (^ and $ match line boundaries) s Dotall (. matches newline)
Test Your Regex
The best way to learn regex is to experiment. Use the Regex Tester to test patterns with live match highlighting. Enter a pattern and test string to see matches in real time.
Tips for Writing Better Regex
- Start simple and build up complexity gradually
- Use non-capturing groups (?:...) when you do not need to extract the match
- Be specific: use \\d instead of [0-9] and \\w instead of [A-Za-z0-9_]
- Use anchors (^ and $) when you need to match the entire string
- Test with edge cases: empty strings, special characters, very long inputs
Regex has a steep learning curve but pays off enormously. Bookmark this cheat sheet and practice with the tester tool to build your pattern-matching skills.