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

\b

Match a word boundary

/\bcat\b/ → "cat" not in "catch"

\B

Match a non-word boundary

/\Bcat\B/ → cat in "catch"

Character Classes

\d

Match digits [0-9]

/\d+/ → "123"

\D

Match non-digits [^0-9]

/\D+/ → "abc"

\w

Match word characters [a-zA-Z0-9_]

/\w+/ → "hello_1"

\W

Match non-word characters

/\W+/ → "!@#"

\s

Match whitespace (space, tab, etc.)

/\s+/ → " "

\S

Match non-whitespace characters

/\S+/ → "hello"

\n

Match newline character

/\n/ → newline

\t

Match tab character

/\t/ → Tab

\0

Match 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)

FlagNameDescription
gglobalGlobal search, find all matches
iignoreCaseCase-insensitive
mmultilineMultiline mode, ^ and $ match start/end of line
sdotAllMake . match all characters including newlines
uunicodeUnicode mode, handle Unicode characters correctly
ystickySticky match, only start from lastIndex position