Regular Expressions
Regular expressions (regex) are patterns used to match character combinations in strings. They’re powerful tools for text processing, validation, and manipulation.Basic Syntax
Common Flags
Basic Patterns
Exact String Match
Use the^ and $ anchors to match the start and end of the string:
Match Empty String
Match Whitespace Sequences
Use the\s meta-sequence to match any whitespace character:
Match Line Breaks
Character Classes
Match Non-Word Characters
Match Alphanumeric, Dashes and Hyphens
Particularly useful when matching URL slugs:Match Letters and Whitespaces
Advanced Patterns
Lookaheads
Pattern not included:Text Inside Brackets
Validation Patterns
Email Validation
Phone Number Validation
URL Validation
Date Validation (DD/MM/YYYY)
Password Strength
Useful Methods
test()
Returns boolean:match()
Returns array of matches:matchAll()
Returns iterator of all matches with groups:replace()
Replace matches:replaceAll()
split()
search()
Returns index of first match:Capture Groups
Basic Groups
Named Groups
Non-Capturing Groups
Practical Examples
Extract All URLs
Chunk String into N-Size Chunks
Camel Case to Snake Case
Strip HTML Tags
Validate Hex Color
Performance Tips
Avoid catastrophic backtracking
Avoid catastrophic backtracking
Be careful with nested quantifiers like
(a+)+ which can cause exponential time complexity. Use possessive quantifiers or atomic groups when possible.Use non-capturing groups
Use non-capturing groups
Use
(?:...) instead of (...) when you don’t need to capture the match. It’s slightly faster.Anchor your patterns
Anchor your patterns
Use
^ and $ anchors when appropriate to avoid searching the entire string.Compile once, use many times
Compile once, use many times
Store regex patterns in variables and reuse them instead of creating new ones each time.
Best Practices
Keep it simple
Keep it simple
Complex regex patterns are hard to read and maintain. Break them into smaller parts or use multiple simpler patterns.
Comment complex patterns
Comment complex patterns
Use the verbose flag in other languages or add comments in your code to explain what the pattern does.
Test thoroughly
Test thoroughly
Test regex patterns with various inputs, including edge cases, to ensure they work as expected.
Consider alternatives
Consider alternatives
For simple operations like checking if a string contains a substring,
includes() is often clearer than regex.