All cheatsheets

Cheatsheets

Regular expressions

Regex tokens — character classes, anchors, quantifiers, groups, and lookarounds.

Visualize

Live regex matcher

Toggle a pattern and watch what it matches — greedy vs lazy on one string.

/<.*>/g1 match

Order 1234 from <b>ada@dev.io</b> ships in <i>3</i> days. Call 555-0100.

Greedy <.*> runs from the first < to the LAST >: one huge match swallowing the text between tags.

43 entries

Character classes7

.

Any character except newline

\d

A digit (0–9)

\D

A non-digit

\w

A word character (a–z, A–Z, 0–9, _)

\W

A non-word character

\s

A whitespace character

\S

A non-whitespace character

Character sets3

[abc]

Any ONE of the listed characters

[^abc]

Any character EXCEPT a, b, c (negated class)

[a-z]

Any character in the range a through z

Anchors4

^

Start of string (or start of line with m flag)

$

End of string (or end of line with m flag)

\b

A word boundary

\B

Not a word boundary

Quantifiers7

* (greedy)

0 or more of the preceding token — greedy

+ (greedy)

1 or more of the preceding token — greedy

? (optional)

0 or 1 — makes the preceding token optional

*? +? ??

Lazy — match as FEW characters as possible

{n}

Exactly n times

{n,}

n or more times

{n,m}

Between n and m times (inclusive)

Groups & backreferences5

(...)

Capturing group

(?:...)

Non-capturing group

(?<name>...)

Named capturing group

\1 \2 …

Backreference — match what group N captured

a|b

Alternation — match a or b

Lookaround4

(?=...)

Positive lookahead — must be followed by …

(?!...)

Negative lookahead — must NOT be followed by …

(?<=...)

Positive lookbehind — must be preceded by …

(?<!...)

Negative lookbehind — must NOT be preceded by …

Escape1

\

Escape the next metacharacter

Flags6

g

Global — find ALL matches, not just the first

i

Case-insensitive — [a-z] also matches [A-Z]

m

Multiline — ^ and $ match the start/end of EACH line

s

Dotall — . also matches newline (\n)

u

Unicode mode — enables full Unicode matching

y

Sticky — match only at the current lastIndex position

Common patterns6

^[\w.+-]+@[\w-]+\.[\w.-]+$

Email address (rough validation)

https?:\/\/([^\/\s]+)(\/[^\s]*)?

URL — capture host and optional path separately

\b(?:\d{1,3}\.){3}\d{1,3}\b

IPv4 address

^#?[0-9a-fA-F]{6}$

Hex colour (#RRGGBB)

(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})

ISO 8601 date (YYYY-MM-DD) with named groups

^[a-z0-9]+(?:-[a-z0-9]+)*$

URL slug (kebab-case, lowercase alphanumeric)