Regular Expression Syntax Guide
Master the art of pattern matching. This comprehensive guide covers every regex syntax element from basic metacharacters to advanced lookaround assertions.
Metacharacters
| Char | Description |
|---|---|
| . | Matches any character except newline |
| ^ | Matches start of string/line |
| $ | Matches end of string/line |
| \d | Matches any digit [0-9] |
| \w | Matches word character [a-zA-Z0-9_] |
| \s | Matches whitespace (space, tab, newline) |
| \b | Matches word boundary |
| \D | Matches non-digit |
| \W | Matches non-word character |
| \S | Matches non-whitespace |
Quantifiers (How Many)
| Syntax | Meaning |
|---|---|
| * | 0 or more |
| + | 1 or more |
| ? | 0 or 1 (optional) |
| {n} | Exactly n times |
| {n,} | n or more times |
| {n,m} | Between n and m times |
| *? | 0 or more (lazy) |
| +? | 1 or more (lazy) |
๐ก Greedy vs Lazy: By default, quantifiers are greedy (match as much as possible). Add ? to make them lazy (match as little as possible).
Character Classes
[abc]Match any single character: a, b, or c
[^abc]Match any character EXCEPT a, b, or c
[a-z]Match any lowercase letter (range)
[0-9A-Fa-f]Match any hexadecimal digit
Groups & Assertions
| Syntax | Type |
|---|---|
| (abc) | Capturing group |
| (?:abc) | Non-capturing group |
| (?<name>) | Named capture group |
| (?=abc) | Positive lookahead |
| (?!abc) | Negative lookahead |
| (?<=abc) | Positive lookbehind |
| (?<!abc) | Negative lookbehind |
| | | Alternation (OR) |
โจ Lookahead/Lookbehind: These "zero-width assertions" check for patterns without including them in the match. Perfect for validating context without consuming characters.
Flags / Modifiers
gGlobalFind all matches, not just the first
iCase-insensitiveIgnore uppercase/lowercase
mMultiline^ and $ match line boundaries
sDotall. also matches newline
uUnicodeEnable full Unicode support
yStickyMatch only from lastIndex position
Usage: /pattern/flags โ /hello/gi matches "Hello", "HELLO", "hello" globally.
Common Patterns Cheat Sheet
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}https?://[\w.-]+(?:/[\w.-]*)*\(?\d{3}\)?[-.]?\d{3}[-.]?\d{4}\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\d{4}-\d{2}-\d{2}#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}โ ๏ธ Escaping Special Characters
To match literal special characters, escape them with backslash:
\. \* \+ \? \^ \$ \| \\ \[ \] \( \) \{}\Example: \$\d+\.\d2 matches "$19.99"
External Resources
Test Your Regex Patterns!
Build and test regular expressions with instant matching feedback.
๐Open Regex Tester