Regex Cheat Sheet
The 90% of regular expressions you actually use: anchors, character classes, quantifiers, groups and escapes — each with a tiny example.
A regular expression describes a pattern of text. The engine walks your string looking for that pattern, so '\d{4}' finds exactly four digits anywhere in the text, and '^ and $' confine a match to the start or end of a line.
The two ideas that unlock everything else: character classes define a set of characters, quantifiers say how many times the previous thing may repeat. Everything else is a refinement of those two.
Anchors
| Pattern | Meaning | Example |
|---|---|---|
^ | Start of the string / line (with m flag) | ^hello |
$ | End of the string / line (with m flag) | world$ |
\b | Word boundary | \bcat\b |
\B | Not a word boundary | \Bcat |
Character classes
| Pattern | Meaning | Example |
|---|---|---|
. | Any character except line breaks | h.t |
\d | Digit (0-9) | \d{4} |
\w | Word character (letters, digits, _) | \w+ |
\s | Whitespace (space, tab, newline) | \s{2} |
\D | Not a digit | \D+ |
\W | Not a word character | \W+ |
\S | Not whitespace | \S{5} |
[abc] | Any one of the listed characters | [aeiou] |
[a-z] | Range of characters | [a-f0-9] |
[^abc] | Any character NOT listed | [^0-9] |
Quantifiers
| Pattern | Meaning | Example |
|---|---|---|
* | 0 or more of the previous | ab*c |
+ | 1 or more of the previous | a+c |
? | 0 or 1 of the previous | colou?r |
{n} | Exactly n times | \d{3} |
{n,} | At least n times | \d{2,} |
{n,m} | Between n and m times | \d{2,4} |
*? | Lazy — match as few as possible | <.*?> |
+? | Lazy + | \d+? |
Groups & alternation
| Pattern | Meaning | Example |
|---|---|---|
(abc) | Capturing group | (\d{2})-(\d{2}) |
(?:abc) | Non-capturing group | (?:ha)+ |
a|b | Alternation (a or b) | cat|dog |
(?<name>x) | Named capture group | (?<year>\d{4}) |
\1 | Backreference to group 1 | (\w)\1 |
Escapes & modifiers
| Pattern | Meaning | Example |
|---|---|---|
\t \n \r | Tab, line feed, carriage return | \r\n |
\u{1F600} | Unicode code point (any length) | \u{1F600} |
\x2e | Hex escape | \x2e |
\/ | Escaped literal slash | \/ |
i / g / m / s | Flags: case-insensitive / global / multiline / dotall | /cat/gi |