Regex Cheat Sheet
Every regex token in one place, grouped by job, each with a concrete example. Bookmark it, copy what you need, and test it live on your own strings.
Anchors & boundaries
| Token | Matches | Example |
|---|---|---|
^ | Start of string (or line with m) | ^Hello |
$ | End of string (or line with m) | end$ |
\b | Word boundary | \bcat\b matches cat not category |
\B | Not a word boundary | \Bing |
Character classes
| Token | Matches |
|---|---|
. | Any char except newline (any char with s flag) |
\d / \D | Digit / non-digit |
\w / \W | Word char [A-Za-z0-9_] / non-word |
\s / \S | Whitespace / non-whitespace |
[abc] | a, b, or c |
[^abc] | Any char except a, b, c |
[a-z] | Range a to z |
Quantifiers
| Token | Repeats |
|---|---|
* | 0 or more |
+ | 1 or more |
? | 0 or 1 (optional) |
{3} | Exactly 3 |
{2,5} | Between 2 and 5 |
{2,} | 2 or more |
*? +? | Lazy versions — match as few as possible |
Groups & alternation
| Token | Meaning |
|---|---|
(abc) | Capturing group |
(?:abc) | Non-capturing group |
(?<name>abc) | Named group |
a|b | a or b |
\1 | Backreference to group 1 |
Lookarounds
| Token | Meaning |
|---|---|
(?=...) | Positive lookahead |
(?!...) | Negative lookahead |
(?<=...) | Positive lookbehind |
(?<!...) | Negative lookbehind |
Flags
g global · i case-insensitive · m multiline (^$ per line) · s dotall (. matches newline) · u unicode · y sticky.
FAQ
What is the difference between \d and [0-9]?
In ASCII text they are equivalent. With the unicode flag, \d can match digits from other scripts, while [0-9] stays restricted to those ten characters.
How do I match a literal dot or bracket?
Escape it with a backslash: \. matches a literal period and \[ matches a literal opening bracket. Inside a character class most metacharacters lose their special meaning.
Why does my regex match too much?
You are probably using a greedy quantifier like .* which grabs as much as possible. Use a lazy version .*? or a negated class like [^"]* to stop at the first delimiter.