A regular expression (regex) is a pattern for matching text. It is built from literal characters plus special tokens that match classes, positions, and repetition. This cheat sheet lists the tokens you reach for most, with a short meaning and example for each.
Character classes
| Token | Meaning | Example |
|---|---|---|
. |
Any character except a line break | a.c matches abc, a-c |
\d |
Any digit 0-9 | \d\d matches 42 |
\D |
Any non-digit | |
\w |
Word character: letter, digit, underscore | |
\W |
Any non-word character | |
\s |
Any whitespace | |
\S |
Any non-whitespace | |
[abc] |
Any one of a, b, or c | |
[^abc] |
Any character except a, b, c | |
[a-z] |
Any character in the range a to z |
Anchors
| Token | Meaning | Example |
|---|---|---|
^ |
Start of the string or line | ^Hi matches Hi at start |
$ |
End of the string or line | end$ matches ...end |
\b |
Word boundary | \bcat\b matches the word cat |
\B |
Not a word boundary |
Quantifiers
| Token | Meaning | Example |
|---|---|---|
* |
0 or more | ab* matches a, ab, abb |
+ |
1 or more | ab+ matches ab, abb |
? |
0 or 1 (optional) | colou?r matches color, colour |
{3} |
Exactly 3 | \d{3} matches 123 |
{2,} |
2 or more | |
{2,5} |
Between 2 and 5 | |
*? |
Lazy: as few as possible |
Groups & alternation
| Token | Meaning | Example |
|---|---|---|
(...) |
Capturing group | (ab)+ repeats ab |
(?:...) |
Non-capturing group | |
(?<name>...) |
Named group | |
| |
Or | cat|dog matches cat or dog |
\1 |
Backreference to group 1 |
Lookaround
| Token | Meaning | Example |
|---|---|---|
(?=...) |
Positive lookahead | \d(?=px) matches digit before px |
(?!...) |
Negative lookahead | |
(?<=...) |
Positive lookbehind | |
(?<!...) |
Negative lookbehind |
Escapes & flags
| Token | Meaning | Example |
|---|---|---|
\. |
A literal dot | |
\\ |
A literal backslash | |
\n |
Newline | |
\t |
Tab | |
g |
Flag: find all matches | |
i |
Flag: case-insensitive | |
m |
Flag: ^ and $ match each line | |
s |
Flag: dot matches newlines |
Frequently Asked Questions
What is a regular expression?
It is a compact pattern used to find, match, or replace text. The same syntax works across most programming languages and editors.
What is the difference between greedy and lazy quantifiers?
Greedy quantifiers like + match as much as possible. Adding a question mark, like +?, makes them lazy and match as little as possible.
What does the i flag do?
The i flag makes matching case-insensitive, so the pattern cat would also match Cat and CAT.
How do I match a literal special character?
Put a backslash before it. For example, use a backslash and a dot to match a real dot rather than any character.
Test your patterns live with our free developer tools, including regex helpers.