Regex Cheat Sheet: Patterns, Syntax & Examples
What are regular expressions?
Regular expressions (regex or regexp) are patterns used to match character combinations in strings. They are a powerful tool for searching, validating, and manipulating text. Every major programming language supports regex: JavaScript, Python, Java, PHP, Go, and more.
Basic syntax
Character classes
.β Matches any character (except newline)\dβ Matches any digit (0-9)\Dβ Matches any non-digit\wβ Matches any word character (a-z, A-Z, 0-9, _)\Wβ Matches any non-word character\sβ Matches any whitespace (space, tab, newline)\Sβ Matches any non-whitespace[abc]β Matches a, b, or c[^abc]β Matches anything except a, b, or c[a-z]β Matches any lowercase letter
Quantifiers
*β 0 or more occurrences+β 1 or more occurrences?β 0 or 1 occurrence (optional){3}β Exactly 3 occurrences{2,5}β Between 2 and 5 occurrences{3,}β 3 or more occurrences
Anchors
^β Start of string (or line in multiline mode)$β End of string (or line in multiline mode)\bβ Word boundary
Groups and alternation
(abc)β Capturing group(?:abc)β Non-capturing groupa|bβ Matches a or b (alternation)(?=abc)β Positive lookahead(?!abc)β Negative lookahead
Common regex patterns
Email validation
^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$
Matches most common email formats. Note: a fully RFC-compliant email regex is extremely complex; this pattern covers 99% of real-world emails.
URL validation
^https?:\/\/[\w.-]+\.[a-zA-Z]{2,}[\/\w.-]*$
Phone number (international)
^\+?[1-9]\d{6,14}$
Date format (YYYY-MM-DD)
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
IP address (IPv4)
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$
Strong password
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Requires: minimum 8 characters, at least one uppercase, one lowercase, one digit, and one special character.
Regex flags
gβ Global: match all occurrences, not just the firstiβ Case-insensitive matchingmβ Multiline: ^ and $ match line boundariessβ Dotall: . matches newlines toouβ Unicode: full Unicode support
Testing your regex
Always test your regular expressions before using them in production. Try our free regex tester to validate patterns in real time with instant highlighting of matches.
Performance tips
- Be specific:
[0-9]is faster than.*for matching digits - Avoid catastrophic backtracking: patterns like
(a+)+can cause exponential time complexity - Use non-capturing groups when you don't need the match:
(?:...)instead of(...) - Anchor your patterns: use
^and$when validating entire strings