Regex Cheatsheet
Regular expression syntax cheatsheet, common patterns reference.
Basic Syntax
.Match any single character (except newline)
/a.c/ → "abc", "a1c"
\Escape special characters
/a\.c/ → "a.c"
|Or (alternation)
/cat
()Capturing group
/(ab)+/ → "abab"
(?:)Non-capturing group
/(?:ab)+/ → "abab" (non-capturing)
[...]Character set, match any one of them
/[aeiou]/ → matches vowels
[^...]Negated character set
/[^0-9]/ → matches non-digits
[a-z]Character range
/[a-zA-Z]/ → matches letters
Quantifiers
*Match the preceding expression 0 or more times
/ab*c/ → "ac", "abc", "abbc"
+Match the preceding expression 1 or more times
/ab+c/ → "abc", "abbc"
?Match the preceding expression 0 or 1 time
/ab?c/ → "ac", "abc"
{n}Match the preceding expression exactly n times
/a{3}/ → "aaa"
{n,}Match the preceding expression at least n times
/a{2,}/ → "aa", "aaa"
{n,m}Match the preceding expression n to m times
/a{2,4}/ → "aa", "aaa", "aaaa"
*?Non-greedy (lazy) version of *
/a.*?b/ → shortest match
+?Non-greedy (lazy) version of +
/a.+?b/ → shortest match
??Non-greedy (lazy) version of ?
/a??b/ → prefers not to match a
Anchors
^Match the beginning of a string
/^Hello/ → starts with Hello
$Match the end of a string
/world$/ → ends with world
\bMatch a word boundary
/\bcat\b/ → "cat" not in "catch"
\BMatch a non-word boundary
/\Bcat\B/ → cat in "catch"
Character Classes
\dMatch digits [0-9]
/\d+/ → "123"
\DMatch non-digits [^0-9]
/\D+/ → "abc"
\wMatch word characters [a-zA-Z0-9_]
/\w+/ → "hello_1"
\WMatch non-word characters
/\W+/ → "!@#"
\sMatch whitespace (space, tab, etc.)
/\s+/ → " "
\SMatch non-whitespace characters
/\S+/ → "hello"
\nMatch newline character
/\n/ → newline
\tMatch tab character
/\t/ → Tab
\0Match NULL character
/\0/ → NULL
Assertions
(?=...)Positive lookahead assertion
/\d(?=px)/ → the 2 in "2px"
(?!...)Negative lookahead assertion
/\d(?!px)/ → the 2 in "2em"
(?<=...)Positive lookbehind assertion
/(?<=\$)\d+/ → the 100 in "$100"
(?<!...)Negative lookbehind assertion
/(?<!\$)\d+/ → the 100 in "100"
Modifiers (Flags)
| Flag | Name | Description |
|---|---|---|
| g | global | Global search, find all matches |
| i | ignoreCase | Case-insensitive |
| m | multiline | Multiline mode, ^ and $ match start/end of line |
| s | dotAll | Make . match all characters including newlines |
| u | unicode | Unicode mode, handle Unicode characters correctly |
| y | sticky | Sticky match, only start from lastIndex position |