Regular Expressions Basics
Regular expressions (regex) are patterns for matching text. They're powerful but can be intimidating at first.
Simple Patterns
// Literal match
/hello/ // Matches "hello"
// Case insensitive
/hello/i // Matches "Hello", "HELLO", etc.
// Global (find all)
/hello/g // Finds all occurrences
Character Classes
/[abc]/ // Matches a, b, or c
/[a-z]/ // Matches any lowercase letter
/[A-Z]/ // Matches any uppercase letter
/[0-9]/ // Matches any digit
/[a-zA-Z0-9]/ // Matches any alphanumeric
// Negation
/[^abc]/ // Matches anything EXCEPT a, b, c
Shorthand Classes
\d // Digit [0-9]
\D // Non-digit [^0-9]
\w // Word char [a-zA-Z0-9_]
\W // Non-word char
\s // Whitespace
\S // Non-whitespace
. // Any character (except newline)
Quantifiers
/a*/ // Zero or more a's
/a+/ // One or more a's
/a?/ // Zero or one a
/a{3}/ // Exactly 3 a's
/a{2,4}/ // 2 to 4 a's
/a{2,}/ // 2 or more a's
Anchors
/^hello/ // Starts with "hello"
/world$/ // Ends with "world"
/^exact$/ // Exactly "exact"
/\bhello\b/ // "hello" as whole word
Common Patterns
// Email (simple)
/^[^\s@]+@[^\s@]+\.[^\s@]+$/
// URL
/https?:\/\/[^\s]+/
// Phone (US)
/\d{3}-\d{3}-\d{4}/
// Date (YYYY-MM-DD)
/\d{4}-\d{2}-\d{2}/