🧩
Regular expressions cheat sheet
Syntax common to JavaScript, Python, PCRE and most modern engines. Test patterns live in the regex tester. Escape a literal special character with a backslash, for example \. for a dot.
Click any pattern to copy it.
Characters and classes
| Pattern | What it does |
|---|
. | Any character except a newline. |
\d \w \s | A digit, a word character (letter, digit, underscore), a whitespace character. |
\D \W \S | The opposites: non-digit, non-word, non-whitespace. |
[abc] | Any one of a, b or c. |
[^abc] | Any character except a, b or c. |
[a-z0-9] | A range: lowercase letters or digits. |
a|b | a or b. |
Anchors and boundaries
| Pattern | What it does |
|---|
^ | Start of the string (or line with the m flag). |
$ | End of the string (or line with the m flag). |
\b | A word boundary. |
\B | Not a word boundary. |
Quantifiers
| Pattern | What it does |
|---|
a* | Zero or more a. |
a+ | One or more a. |
a? | Zero or one a (optional). |
a{3} | Exactly three a. |
a{2,5} | Between two and five a. |
a{2,} | Two or more a. |
.*? | Lazy: as few characters as possible. |
a+? | Lazy one or more. |
Groups and references
| Pattern | What it does |
|---|
(abc) | Capture group. |
(?:abc) | Non-capturing group. |
(?<name>abc) | Named capture group (JavaScript and PCRE; Python uses (?P<name>abc)). |
\1 | Backreference to the first group. |
$1 | In a replacement string: the first captured group. |
Lookarounds
| Pattern | What it does |
|---|
a(?=b) | a only if followed by b (positive lookahead). |
a(?!b) | a only if not followed by b. |
(?<=b)a | a only if preceded by b (lookbehind). |
(?<!b)a | a only if not preceded by b. |
Flags
| Pattern | What it does |
|---|
i | Case-insensitive. |
g | Global: find all matches (JavaScript). |
m | Multiline: ^ and $ match at each line. |
s | Dot also matches newlines. |
u | Unicode mode. |
Common patterns
| Pattern | What it does |
|---|
^\d+$ | Digits only. |
^[a-z0-9]+(?:-[a-z0-9]+)*$ | A URL slug such as my-post-title. |
^\d{4}-\d{2}-\d{2}$ | A date in YYYY-MM-DD form (format only, not validity). |
^#?[0-9a-fA-F]{6}$ | A six-digit hex colour. |
^[^\s@]+@[^\s@]+\.[^\s@]+$ | A simple email check. Truly validating email needs a confirmation message. |
^(?:\d{1,3}\.){3}\d{1,3}$ | A loose IPv4 shape (it does not check that each part is 255 or less). |
https?://[^\s]+ | A basic URL finder. |
^\s+|\s+$ | Leading or trailing whitespace (for trimming). |
\b(\w+)\s+\1\b | A repeated word, such as 'the the'. |
Frequently asked questions
What is the difference between greedy and lazy matching?
Greedy quantifiers (*, +) match as much as possible; adding ? makes them lazy and match as little as possible. On <b>a</b><b>b</b>, <.*> matches the whole string while <.*?> matches just the first tag.
Why does my regex fail on newlines?
The dot does not match newlines by default. Use the s flag, or a class such as [\s\S].
More Programming & Tooling cheat sheets