Regex
Regex Cheatsheet
Quick reference for regular expression syntax including character classes, quantifiers, anchors, groups, and lookaround assertions.
Character Classes
| Pattern | Description |
|---|
. | Any character except newline |
\d | Digit [0-9] |
\D | Non-digit [^0-9] |
\w | Word character [a-zA-Z0-9_] |
\W | Non-word character |
\s | Whitespace [ \t\n\r\f\v] |
\S | Non-whitespace |
[abc] | Any of a, b, or c |
[^abc] | Not a, b, or c |
[a-z] | Range: a to z |
[a-zA-Z] | Any letter |
[0-9] | Any digit |
Anchors
| Pattern | Description |
|---|
^ | Start of string (or line with m flag) |
$ | End of string (or line with m flag) |
\b | Word boundary |
\B | Non-word boundary |
\A | Start of string (absolute) |
\Z | End of string (absolute) |
Quantifiers
| Pattern | Description |
|---|
* | 0 or more |
+ | 1 or more |
? | 0 or 1 |
{3} | Exactly 3 |
{3,} | 3 or more |
{3,5} | Between 3 and 5 |
*? | 0 or more (lazy) |
+? | 1 or more (lazy) |
?? | 0 or 1 (lazy) |
Groups & References
| Pattern | Description |
|---|
(abc) | Capturing group |
(?:abc) | Non-capturing group |
(?<name>abc) | Named capturing group |
\1 | Backreference to group 1 |
\k<name> | Backreference to named group |
(a|b) | Alternation: a or b |
Lookaround
| Pattern | Description |
|---|
(?=abc) | Positive lookahead |
(?!abc) | Negative lookahead |
(?<=abc) | Positive lookbehind |
(?<!abc) | Negative lookbehind |
Flags
| Flag | Description |
|---|
g | Global: match all occurrences |
i | Case-insensitive |
m | Multiline: ^ and $ match line boundaries |
s | Dotall: . matches newline |
u | Unicode support |
x | Extended: allow whitespace and comments |
Escape Sequences
| Pattern | Description |
|---|
\\ | Literal backslash |
\. | Literal dot |
\* | Literal asterisk |
\+, \?, \^, \$ | Literal special characters |
\[, \], \(, \) | Literal brackets/parens |
\{, \}, | | Literal braces/pipe |
Common Patterns
# Email (simplified)
[\w.-]+@[\w.-]+\.\w{2,}
# URL
https?://[\w\-.]+(:\d+)?(/\S*)?
# IPv4 address
\b\d{1,3}(\.\d{1,3}){3}\b
# Date (YYYY-MM-DD)
\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])
# Phone (US)
\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}
# Hex color
#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})
# HTML tag
<\/?[\w\s="'-]*\/?>
# Whitespace trimming
^\s+|\s+$
# Duplicate words
\b(\w+)\s+\1\b
JavaScript Usage
const re = /pattern/flags;
re.test("string"); // true/false
"string".match(re); // match array or null
"string".replace(re, "new"); // replaced string
"string".split(re); // split into array
[..."string".matchAll(re)]; // all matches (with g flag)
Python Usage
import re
re.search(r"pattern", string) # First match or None
re.match(r"pattern", string) # Match at start only
re.findall(r"pattern", string) # List of all matches
re.sub(r"old", "new", string) # Replace all
re.split(r"pattern", string) # Split by pattern
re.compile(r"pattern") # Precompile for reuse