Regex cheatsheet

Copy-ready JavaScript regex patterns

All content runs locally in your browser

Last updated: February 7, 2026
Frank Zhao - Creator
CreatorFrank Zhao

Normal characters

ExpressionDescription
. or [^\n\r]any character excluding a newline or carriage return
[A-Za-z]alphabet
[a-z]lowercase alphabet
[A-Z]uppercase alphabet
\d or [0-9]digit
\D or [^0-9]non-digit
_underscore
\w or [A-Za-z0-9_]alphabet, digit or underscore
\W or [^A-Za-z0-9_]inverse of w
\Sinverse of s

Whitespace characters

ExpressionDescription
space
\ttab
\nnewline
\rcarriage return
\sspace, tab, newline or carriage return

Character set

ExpressionDescription
[xyz]either x, y or z
[^xyz]neither x, y nor z
[1-3]either 1, 2 or 3
[^1-3]neither 1, 2 nor 3
  • Think of a character set as an OR operation on the single characters that are enclosed between the square brackets.
  • Use ^ after the opening [ to “negate” the character set.
  • Within a character set, . means a literal period.

Characters that require escaping

Outside a character set

ExpressionDescription
\.period
\^caret
\$dollar sign
\|pipe
\\back slash
\/forward slash
\(opening bracket
\)closing bracket
\[opening square bracket
\]closing square bracket
\{opening curly bracket
\}closing curly bracket

Inside a character set

ExpressionDescription
\\back slash
\]closing square bracket
  • A ^ must be escaped only if it occurs immediately after the opening [ of the character set.
  • A - must be escaped only if it occurs between two alphabets or two digits.

Quantifiers

ExpressionDescription
{2}exactly 2
{2,}at least 2
{2,7}at least 2 but no more than 7
*0 or more
+1 or more
?exactly 0 or 1
  • The quantifier goes after the expression to be quantified.

Boundaries

ExpressionDescription
^start of string
$end of string
\bword boundary
  • How word boundary matching works:
    • At the beginning of the string if the first character is \w.
    • Between two adjacent characters within the string, if the first character is \w and the second character is \W.
    • At the end of the string if the last character is \w.

Matching

ExpressionDescription
foo|barmatch either foo or bar
foo(?=bar)match foo if it’s before bar
foo(?!bar)match foo if it’s not before bar
(?<=bar)foomatch foo if it’s after bar
(?<!bar)foomatch foo if it’s not after bar

Grouping and capturing

ExpressionDescription
(foo)capturing group; match and capture foo
(?:foo)non-capturing group; match foo but without capturing foo
(foo)bar\1\1 is a backreference to the 1st capturing group; match foobarfoo
  • Capturing groups are only relevant in the following methods:
    • string.match(regexp)
    • string.matchAll(regexp)
    • string.replace(regexp, callback)
  • \N is a backreference to the Nth capturing group. Capturing groups are numbered starting from 1.

References and tools

Introduction / overview

This Regex cheatsheet is a fast reference for JavaScript regular expressions (RegExp): boundaries, matching, groups, escaping rules, and the most common building blocks you’ll see in day-to-day coding.

If you’re debugging a tricky pattern, pair this page with our Regex tester to try real inputs and verify edge cases.

Who is this for?

  • Frontend and backend developers writing validators, parsers, and text transforms.
  • Data and ops folks cleaning logs or extracting IDs.
  • Anyone who wants a quick reminder of escaping and lookaround syntax.

When it saves time

When you already know what you want (for example “match a whole word” or “capture a group”), but you don’t want to remember the exact syntax.

The cheatsheet focuses on practical patterns and plain-English meaning. If you need help experimenting, open the tester and iterate: write a pattern, try inputs, and add edge cases.

How to use / quick start

1

Start with the smallest correct block

Pick one row from the tables (for example, boundaries like b\\b) and validate it on sample text.

2

Add repetition with quantifiers

Use ++, *, or range quantifiers like {2,7}\{2,7\}.

Length n\text{Length } n\in{2,3,4,5,6,7}\{2,3,4,5,6,7\}\Rightarrow2n72 \le n \le 7
3

Capture only what you need

Use ()( ) when you need a group (for extraction or backreferences), and use non-capturing (?:)(?: ) when you don’t.

4

Test edge cases and performance

Try empty strings, very long strings, and “almost matches.” If input can come from users, avoid patterns that can blow up runtime.

How to interpret results

  • A match means the engine found a substring that satisfies the pattern; groups tell you which parts were captured.
  • If a pattern matches “too much,” it’s often because of greedy quantifiers. Try a lazy variant like ?*?.

Real-world examples

Extract numbers from a string

Input: "Order #A19: 3 items"

Pattern: /\\d+/g

Result: [19, 3][19,\ 3] (two matches)

Apply it to extract IDs, counts, or timestamps.

Match a whole word (not a substring)

Input: "cat scatter catalog"

Pattern: /\\bcat\\b/g

Result: matches only the standalone cat\text{cat}

Useful for search and replace without accidental partial matches.

Validate a simple slug

Input: "my-post-2026"

Pattern: /^[a-z0-9-]+$/

Result: pass / fail

Keep it strict when the value is used in URLs.

Use lookaround to match context

Input: "total=42; tax=7"

Pattern: /(?<=total=)\\d+/

Result: 4242

You match the number without consuming the prefix.

Want to try these instantly? Open Regex tester and paste the input + pattern.

Common scenarios

Form validation

Basic checks like only digits or a simple slug.

Log parsing

Extract IDs, status codes, and timestamps from messy text.

Search & replace

Use boundaries to avoid changing partial words.

Data cleanup

Normalize whitespace and remove unwanted characters.

Content moderation

Quick pattern checks (but don’t rely on regex alone).

Preprocessing for analytics

Segment text before counting or aggregating.

When regex may not be a good fit

  • Parsing nested structures (like full HTML) is often better with a real parser.
  • User-controlled inputs can be risky if the pattern is complex and backtracks heavily.

Tips & best practices

Pro tip: Write the simplest pattern that works, then tighten it. Regex gets hard when you try to be clever too early.

  • Prefer explicit character sets over . when you know what you expect.
  • Anchor validations with ^ and $.
  • In JavaScript strings, escape backslashes: "\\\\d+" represents \\d+.
  • Avoid nested ambiguous quantifiers (for example (.*)+) on user input.
  • Test with near-misses: if you expect cat\text{cat}, test scatter\text{scatter} too.

Calculation method / pattern logic

Regex isn’t “calculation” in the math sense, but the rules are still precise. Here are the two ideas that explain most surprises: boundaries and quantifiers.

Quantifier ranges

A range quantifier like {n,m}\{n,m\} means “repeat between nn and mm times.”

If a token repeats n to m times, then nkm\text{If a token repeats } n \text{ to } m \text{ times, then } n \le k \le m

Word boundaries

The boundary b\\b matches a transition between a “word character” and a “non-word character.” In JavaScript, that word set is roughly:

w[A-Za-z0-9_]\\w \approx [A\text{-}Za\text{-}z0\text{-}9\_]

Lookaround is “match without consuming”

A lookahead/behind checks context but doesn’t become part of the match. It’s handy when you want to keep the output clean.

Match x\text{Match } x only if preceded by y\text{ only if preceded by } y\Rightarrow(?<=y)x(?<=y)x

Related concepts

Greedy vs lazy quantifiers

Quantifiers are greedy by default (they match as much as possible). Adding ?? makes them lazy.

..* (greedy) \text{ (greedy) }\Rightarrow.?.*? (lazy) \text{ (lazy) }

Engine differences

Not all regex engines support the same features (for example, lookbehind). If a pattern fails in another language, verify engine support and syntax.

Frequently asked questions

1) Why doesn’t my dot match newlines?

In JavaScript, . doesn’t match newline by default. Use the ss flag (dotAll) if you truly want dot to include newlines.

2) What’s the difference between capturing and non-capturing groups?

Capturing ( ) stores the matched substring for extraction/backreferences. Non-capturing (?: ) groups without creating a numbered capture.

3) Why does my pattern match more than expected?

It’s usually greediness. Try a lazy quantifier like ?*? or tighten the character set.

4) Why do I get different results across languages?

Different engines support different features and edge-case behavior (Unicode, lookbehind, possessive quantifiers, etc.). Always check your target runtime.

5) Is regex safe for user input?

It can be, but avoid patterns that may backtrack catastrophically. If you must run complex patterns on user text, limit input length and test worst-case strings.

Limitations / disclaimers

  • This guide is a practical reference, not an exhaustive spec for every regex feature or every engine.
  • Don’t rely on regex alone for security-sensitive validation; combine it with proper parsing and server-side checks.
  • For untrusted input, be mindful of performance (Regex DoS / ReDoS) and consider timeouts/limits where possible.

External references