Regex cheat sheet
The tokens you actually use, one screen each, with a live tester at the bottom of the page to try them immediately.
Character classes
- .
- any character except newline
- \d \D
- digit / not a digit
- \w \W
- word character / not one
- \s \S
- whitespace / not whitespace
- [abc]
- any of a, b or c
- [^abc]
- anything except a, b, c
- [a-z0-9]
- ranges combine freely
Quantifiers
- *
- zero or more
- +
- one or more
- ?
- zero or one (optional)
- {3}
- exactly three
- {2,5}
- between two and five
- {2,}
- two or more
- *? +?
- lazy: match as little as possible
Anchors and boundaries
- ^
- start of text (or line with m)
- $
- end of text (or line with m)
- \b
- word boundary
- \B
- not a word boundary
Flags
- g i m
- all matches / ignore case / multiline
- s u
- dot matches newline / unicode
Groups and alternation
- (abc)
- capture group, $1 in replace
- (?:abc)
- group without capturing
- (?<name>)
- named capture group
- a|b
- a or b
- \1
- backreference to group 1
- (?=x) (?!x)
- lookahead: followed / not followed by x
- (?<=x)
- lookbehind: preceded by x
Try the tokens live
FAQ
Frequently asked questions
What is the difference between \d, \w and \s?
\d is any digit, \w is a word character (letters, digits, underscore) and \s is any whitespace including tabs and newlines. Their capitals negate them: \D, \W and \S match everything else.
When do I need to escape a character?
When it has a special meaning: . * + ? ^ $ ( ) [ ] { } | \ and /. Put a backslash in front to match the literal character, so \. matches an actual full stop.
What is the difference between * and +?
* means zero or more, + means one or more. a* happily matches an empty string; a+ needs at least one a. {2,5} sets an explicit range.
What does anchoring with ^ and $ do?
^ pins the match to the start and $ to the end. Without anchors, a validation pattern can pass because it matched somewhere inside the input, the classic validation bug.
What is a non-capturing group?
(?:...) groups tokens for quantifiers or alternation without creating a numbered capture, keeping $1 and friends pointing where you expect.
What is lookahead?
(?=...) requires something to follow without including it in the match, and (?!...) requires it not to follow. Password rules like "contains a digit" are the everyday use.
More tools