How to Write Regex Patterns — Complete Guide
Regular expressions are a powerful tool for text processing, validation, and data extraction. Test and debug your patterns with our Regex Tester.
Regex Basics: Core Concepts
Literal Characters /hello/ Matches "hello" anywhere in the string Dot /h.llo/ Matches "hallo", "hxllo", "h9llo" (any char) Character Class /h[ae]llo/ Matches "hallo" or "hello" only Negated Class /h[^ae]llo/ Matches "hxllo" but not "hallo" or "hello" Start Anchor /^hello/ Matches "hello" only at string start End Anchor /hello$/ Matches "hello" only at string end
Common Regex Patterns
Email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
URL: /^https?:\/\/[^\s]+$/
Phone (US): /^\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}$/
Password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/
Hex Color: /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/
IP v4: /^(\d{1,3}\.){3}\d{1,3}$/Regex Quantifiers
* Zero or more
Matches 0 or more occurrences. a*b matches "b", "ab", "aab"
+ One or more
Matches 1 or more. a+b matches "ab", "aab", not "b"
? Zero or one
Makes preceding char optional. colou?r matches "color" and "colour"
{n} Exactly n
\d{3} matches exactly 3 digits
{n,} n or more
a{2,} matches "aa", "aaa", "aaaa"...
{n,m} Between n and m
\w{3,6} matches 3 to 6 word characters
Tips for Writing Better Regex
Start simple and build up. Begin with literal matches, then add flexibility. Test each addition in our Regex Tester.
Use anchors to avoid false matches. Always use ^ and $ when validating entire strings to prevent partial matches.
Escape special characters. Use \\ before . * + ? [ ] ( ) ^ $ | \\ to match them literally.
Use non-capturing groups. Use (?:pattern) instead of (pattern) when you do not need to capture the match for better performance.