85 entries · 9 sections
Regex Cheat Sheet
Regular expression syntax in one place: anchors, character classes, quantifiers, groups, lookaround and flags, plus the patterns worth keeping. Where JavaScript and PCRE (Perl, PHP, Python, Java, grep -P) disagree, the difference is called out rather than glossed over.
Anchors and boundaries
| Syntax | What it does |
|---|---|
^ | Start of the string — or the start of any line when the multiline flag is on. |
$ | End of the string — or the end of any line under multiline. |
\b | Word boundary: the position between a word character and a non-word character. |
\B | Not a word boundary. |
\A | Absolute start of the string, ignoring multiline. PCRE, Python and Java; not JavaScript. |
\z | Absolute end of the string. PCRE and Java (Python spells it \Z); not JavaScript. |
\Z | End of string, allowing one trailing newline, in PCRE and Java. In Python \Z is the absolute end. |
\G | The position where the previous match ended. PCRE and Java; not JavaScript. |
Character classes
| Syntax | What it does |
|---|---|
. | Any character except a newline, unless the dotall flag (s) is set. |
[abc] | Any one of a, b or c. |
[^abc] | Any character that is not a, b or c. |
[a-z] | Any character in the range a to z. Ranges use the character's code point. |
[a-zA-Z0-9_] | Several ranges in one class. |
\d / \D | A digit / anything that is not a digit. |
\w / \W | A word character, meaning [A-Za-z0-9_] / anything else. |
\s / \S | Any whitespace, including tabs and newlines / any non-whitespace. |
[[:alpha:]] | POSIX class for letters. Works in PCRE and grep -E; not in JavaScript. |
\p{L} | Any Unicode letter. JavaScript requires the u or v flag for this. |
\p{Script=Greek} | Any character belonging to a named Unicode script. |
[\d.-] | Inside a class, put - last or escape it so it is a literal hyphen, not a range. |
Quantifiers
| Syntax | What it does |
|---|---|
* | Zero or more of the preceding token. |
+ | One or more. |
? | Zero or one — makes the preceding token optional. |
{3} | Exactly three. |
{2,} | Two or more. |
{2,5} | Between two and five, inclusive. |
*? +? ?? {n,m}? | Lazy quantifiers: match as few characters as possible. The fix for a greedy .* swallowing the line. |
*+ ++ ?+ {n,m}+ | Possessive quantifiers: match greedily and never give characters back. PCRE and Java; not JavaScript. |
Groups and alternation
| Syntax | What it does |
|---|---|
(abc) | Capturing group. Also groups tokens so a quantifier applies to all of them. |
(?:abc) | Non-capturing group: groups without allocating a capture number. |
(?<name>abc) | Named capturing group. JavaScript since ES2018, PCRE and Python — Python also accepts (?P<name>abc). |
a|b | Alternation: a or b. It has the lowest precedence, so wrap it in a group when it is part of a bigger pattern. |
\1 | Backreference to whatever group 1 captured. |
\k<name> | Backreference to a named group. |
$1 or \1 in replacements | Refer to a capture in the replacement string. JavaScript uses $1, most other tools use \1. |
(?i)abc | Inline flag: case-insensitive from here on. PCRE, Python and Java; not JavaScript. |
(?i:abc) | Scoped inline flag, applying only to that group. |
(?>abc) | Atomic group: once it matches, it never backtracks. PCRE and Java; not JavaScript. |
Lookahead and lookbehind
| Syntax | What it does |
|---|---|
(?=abc) | Positive lookahead: what follows is abc, but those characters are not consumed. |
(?!abc) | Negative lookahead: what follows is not abc. |
(?<=abc) | Positive lookbehind: what precedes is abc. |
(?<!abc) | Negative lookbehind: what precedes is not abc. |
^(?=.*[a-z])(?=.*\d).{8,}$ | Stacked lookaheads as a password rule: at least one letter, one digit, eight characters. |
\d+(?= ?kg) | Match the number only when kg follows it — and capture the number alone. |
(?<=\$)\d+(?:\.\d{2})? | Match an amount only when it follows a dollar sign. |
\b(?!test)\w+ | A word that does not start with test. |
Flags and modifiers
| Syntax | What it does |
|---|---|
g | Global: find every match rather than stopping at the first (JavaScript). |
i | Case-insensitive matching. |
m | Multiline: ^ and $ also match at line breaks. |
s | Dotall: . also matches newline characters. |
u | Unicode mode in JavaScript. Required for \p{...} and for correct handling of astral characters. |
v | JavaScript's newer Unicode-sets mode (ES2024), adding set operations inside character classes. |
y | Sticky: the match must begin exactly at lastIndex (JavaScript). |
d | Emit match indices for each capture group in the result (JavaScript, ES2022). |
x | Extended mode: ignore whitespace and allow # comments in the pattern. PCRE and Python (re.X); not JavaScript. |
Escapes and literal characters
| Syntax | What it does |
|---|---|
\. \* \+ \? \( \) | Escape a metacharacter to match it literally. |
\\ | A literal backslash. In a language string literal you often have to double it again. |
\/ | A literal slash inside a /.../ JavaScript regex literal. |
\n \r \t | Newline, carriage return and tab. |
\xFF | A character by two-digit hexadecimal code. |
\uFFFF | A UTF-16 code unit by hexadecimal value (JavaScript). |
\u{1F600} | A full Unicode code point. Needs the u flag in JavaScript. |
\Q...\E | Treat everything between as literal text. PCRE and Java; not JavaScript or Python. |
Patterns worth keeping
| Syntax | What it does |
|---|---|
^\s*$ | A blank or whitespace-only line. |
\s+$ | Trailing whitespace — for stripping it. |
^[\w.+-]+@[\w-]+\.[\w.]+$ | A pragmatic email shape. Do not attempt full RFC 5322; validate by sending a mail. |
https?://[^\s"'<>]+ | A URL sitting inside prose. |
^(?:\d{1,3}\.){3}\d{1,3}$ | The shape of an IPv4 address. It does not check that each octet is 0-255. |
^\d{4}-\d{2}-\d{2}$ | An ISO date, YYYY-MM-DD. |
^#{1,6}\s | A Markdown heading line. |
(\b\w+\b)\s+\1 | A doubled word, using a backreference. |
[^\x00-\x7F] | Any non-ASCII character. |
^(?!.*\bfoo\b).*$ | A whole line that does not contain the word foo. |
Using regex in JavaScript
| Syntax | What it does |
|---|---|
/re/.test(str) | True or false: does the pattern match anywhere? |
str.match(/re/) | First match with its capture groups, or null. |
str.match(/re/g) | An array of every full match. Capture groups are not returned when g is set. |
str.matchAll(/re/g) | An iterator of full match objects, groups and indices included. Requires the g flag. |
re.exec(str) | The next match, advancing lastIndex when the g or y flag is set. |
str.replace(/re/g, "$1") | Replace every match, referring to capture group 1 as $1. |
str.replace(/re/g, (m, p1) => ...) | Replace using a function of the match and its groups. |
str.replaceAll("a", "b") | Replace every literal occurrence without a regex (ES2021). |
str.split(/\s*,\s*/) | Split on a pattern rather than a fixed string. |
new RegExp(src, "gi") | Build a pattern from a string. Remember that every backslash has to be doubled. |
m.groups.name | Read a named capture out of a match result. |
RegExp.escape(str) | Escape user input for safe use in a pattern (ES2025; use a manual replace as a fallback). |
Worth knowing
- Greedy quantifiers are the single most common regex bug. /<.*>/ matches from the first < to the last > on the line; /<.*?>/ matches one tag. When a pattern grabs far too much, add a ? to the quantifier before you rewrite anything else.
- Lookbehind is not universal. JavaScript has supported it since ES2018 (Safari only from 16.4), and Python's re module allows only fixed-width lookbehind — (?<=ab|abc) is an error there. Test lookbehind on your actual runtime before relying on it.
- Nesting quantifiers such as (a+)+ can make a pattern take exponential time on input that nearly matches — catastrophic backtracking, and a real denial-of-service vector when the input comes from users. Prefer atomic groups or possessive quantifiers where your engine has them, and never build a pattern by concatenating unescaped user input.
Try a snippet instead of reading about it
Reference is faster when you can run the thing. Paste a snippet into AltF Code, the free in-browser editor — real syntax highlighting for HTML, CSS, JavaScript, Python, SQL, JSON and more, with HTML, CSS and JavaScript running live in the preview. No install and no sign-up.
Open the editorRegex — common questions
- What is the difference between greedy and lazy quantifiers?
- A greedy quantifier such as .* takes as much as it can and then backtracks until the rest of the pattern fits, so it matches to the last possible position. A lazy quantifier such as .*? takes as little as it can and expands only as needed, so it stops at the first possible position. Same characters, opposite appetite.
- Does JavaScript regex support lookbehind?
- Yes. (?<=...) and (?<!...) have been part of the language since ES2018 and work in every current browser and in Node, with Safari the late arrival at 16.4. Unlike Python, JavaScript allows variable-length lookbehind, so (?<=ab|abcd) is valid.
- How do I match a literal dot, slash or backslash?
- Escape it with a backslash: \. for a dot, \/ for a slash inside a /.../ literal, and \\ for a backslash itself. Inside a character class most metacharacters lose their meaning, so [.] also matches a literal dot. When you build a pattern from a string in code, every backslash has to be doubled again for the string literal.
- Why does my pattern work on regex101 but not in my code?
- Almost always a flavour or escaping difference. regex101 defaults to PCRE, which has \A, \Z, atomic groups, possessive quantifiers and inline (?i) flags that JavaScript does not. And if you built the pattern with new RegExp("\d+") the string literal ate the backslash — it needs to be "\\d+".