Regular Expression Cheat Sheet
Regex syntax cheat sheet: metacharacters, character classes, anchors, quantifiers, groups and look-around assertions with notes for quick lookup while debugging.
| Token | Meaning |
|---|---|
| . | Any single character (newline excluded by default) |
| \d | Digit [0-9] |
| \D | Non-digit |
| \w | Word character [A-Za-z0-9_] |
| \W | Non-word character |
| \s | Whitespace (space/tab/newline) |
| \S | Non-whitespace |
| ^ | Start of string or line |
| $ | End of string or line |
| \b | Word boundary |
| \B | Non-word boundary |
| * | Previous item 0 or more times (greedy) |
| + | Previous item 1 or more times (greedy) |
| ? | Previous item 0 or 1 time |
| {n} | Exactly n times |
| {n,} | At least n times |
| {n,m} | Between n and m times |
| (...) | Capturing group |
| (?:...) | Non-capturing group |
| [...] | Character class (match any one) |
| [^...] | Negated character class |
| | | Alternation (OR) |
| \1 | Backreference to group 1 |
| (?=...) | Positive lookahead |
| (?!...) | Negative lookahead |
| (?<=...) | Positive lookbehind |
| (?<!...) | Negative lookbehind |
Frequently Asked Questions
What is the difference between greedy and lazy quantifiers?
Greedy (*, +) matches as much as possible; adding ? after (*?, +?) makes it lazy, matching as little as possible. On "<a>1</a><a>2</a>", <.*> grabs to the last </a>, while <.*?> stops at the first.
How do I make . match newlines too?
By default . does not match newlines. Enable dotall mode (JS s flag, PHP/Python DOTALL) or use a class like [\s\S] that works in every engine.
What is the difference between a character class and a group?
[abc] matches a single char (a, b or c); (abc) is a whole sequence matching the literal "abc" and can be quantified as a unit, e.g. (abc)+.
What regex performance issues should I watch?
Beware catastrophic backtracking: nested quantifiers like (a+)+ cause exponential backtracking on failure. Use explicit classes and anchors ^ $ to narrow scope; use possessive/atomic groups when needed.