HomeToolsRegexRegex Cheat Sheet

Regex Cheat Sheet

An interactive, searchable reference guide for regular expressions with inline pattern matching visualization.

Regex
Wildcard (Dot)Character Classes
.

Matches any single character except line terminators (newline).

Demo Matcher (Edit Text)/./g
cat. 9!
DigitCharacter Classes
\d

Matches any digit character (0-9). Equivalent to [0-9].

Demo Matcher (Edit Text)/\d/g
Order #4521 completed.
Non-DigitCharacter Classes
\D

Matches any character that is not a digit. Equivalent to [^0-9].

Demo Matcher (Edit Text)/\D/g
Phone: 555-1234
Word CharacterCharacter Classes
\w

Matches any alphanumeric character (letters, numbers) and underscore. Equivalent to [A-Za-z0-9_].

Demo Matcher (Edit Text)/\w/g
User_99! ID#45
Non-Word CharacterCharacter Classes
\W

Matches any character that is not a word character. Equivalent to [^A-Za-z0-9_].

Demo Matcher (Edit Text)/\W/g
User_99! ID#45
WhitespaceCharacter Classes
\s

Matches any whitespace character (spaces, tabs, newlines).

Demo Matcher (Edit Text)/\s/g
A B C D
Non-WhitespaceCharacter Classes
\S

Matches any character that is not whitespace.

Demo Matcher (Edit Text)/\S/g
A B C D
Character SetCharacter Classes
[abc]

Matches any single character listed inside the square brackets (a, b, or c).

Demo Matcher (Edit Text)/[cag]/g
the cat and the dog
Negated Character SetCharacter Classes
[^abc]

Matches any single character NOT listed inside the brackets.

Demo Matcher (Edit Text)/[^cat ]/g
cat dog
Range SetCharacter Classes
[a-z]

Matches a character within the specified range (in this case, lowercase a to z).

Demo Matcher (Edit Text)/[a-zA-Z]/g
Room 101-B
Zero or MoreQuantifiers
*

Matches the preceding token 0 or more times.

Demo Matcher (Edit Text)/ab*/g
a ab abb abbb ac
One or MoreQuantifiers
+

Matches the preceding token 1 or more times.

Demo Matcher (Edit Text)/ab+/g
a ab abb abbb ac
Zero or One (Optional)Quantifiers
?

Matches the preceding token 0 or 1 time, making it optional.

Demo Matcher (Edit Text)/colou?r/g
color and colour
Exact CountQuantifiers
{n}

Matches the preceding token exactly n times.

Demo Matcher (Edit Text)/\b\d{3}\b/g
1 12 123 1234 12345
Minimum CountQuantifiers
{n,}

Matches the preceding token n or more times.

Demo Matcher (Edit Text)/\b\d{3,}\b/g
1 12 123 1234 12345
Range CountQuantifiers
{n,m}

Matches the preceding token between n and m times.

Demo Matcher (Edit Text)/\b\d{2,4}\b/g
1 12 123 1234 12345
Start of Line / StringAnchors
^

Matches the start of the string, or the start of a line if multiline flag (m) is set.

Demo Matcher (Edit Text)/^hello/gm
hello world hello developers
End of Line / StringAnchors
$

Matches the end of the string, or the end of a line if multiline flag (m) is set.

Demo Matcher (Edit Text)/\.[a-z]+$/gm
file.txt code.ts
Word BoundaryAnchors
\b

Matches a position where a word character is adjacent to a non-word character (or start/end of string).

Demo Matcher (Edit Text)/\bcat\b/g
cat category bobcat copycat
Non-word BoundaryAnchors
\B

Matches any position that is NOT a word boundary.

Demo Matcher (Edit Text)/\Bcat\B/g
cat category bobcat copycat
Capturing GroupGroups & Captures
(abc)

Groups multiple tokens together and creates a capture group for extracting substrings.

Demo Matcher (Edit Text)/(ha)/g
ha-ha ho-ho
Non-Capturing GroupGroups & Captures
(?:abc)

Groups tokens without creating a separate capture group for extraction.

Demo Matcher (Edit Text)/(?:ha)/g
ha-ha ho-ho
Alternation (OR)Groups & Captures
a|b

Matches either the pattern on the left or the pattern on the right side of the pipe.

Demo Matcher (Edit Text)/cat|dog/g
cat dog bird
Positive LookaheadLookarounds
(?=abc)

Asserts that the given pattern matches immediately after the current position, without consuming text.

Demo Matcher (Edit Text)/\d+(?=px)/g
100px 50% 200px 80%
Negative LookaheadLookarounds
(?!abc)

Asserts that the given pattern does NOT match immediately after the current position.

Demo Matcher (Edit Text)/\b\d+(?!px)\b/g
100px 50% 200px 80%
Positive LookbehindLookarounds
(?<=abc)

Asserts that the given pattern matches immediately before the current position, without consuming text.

Demo Matcher (Edit Text)/(?<=\$)\d+/g
$100 €50 ¥200 $80
Negative LookbehindLookarounds
(?<!abc)

Asserts that the given pattern does NOT match immediately before the current position.

Demo Matcher (Edit Text)/(?<!\$)\b\d+\b/g
$100 €50 ¥200 $80

A regex reference you can perturb

Regular-expression syntax becomes memorable when you can change the subject text and watch the match move. This regex cheat sheet combines a searchable reference with small interactive demonstrations. Each card names a token, explains its role, shows the demo pattern and flags, and highlights matches in editable sample text. Its copy button copies the syntax token for use in your own pattern.

Search by symbol, name, or wording such as \w, “boundary,” or “optional.” Category tabs narrow the cards to Character Classes, Quantifiers, Anchors, Groups & Captures, or Lookarounds. Search and category filters work together, so an overly narrow combination can produce no results.

The demos use the browser’s JavaScript RegExp engine. That detail matters: regex dialects overlap, but Python, PCRE2, Java, .NET, Ruby, Rust, RE2, POSIX tools, databases, and editors differ in supported syntax and behavior. Learn the concept here, then confirm it in the engine where the pattern will run.

Begin with what one character can be

Character classes describe a single consumed position.

  • . is a wildcard for one character except line terminators under the demo’s default behavior. JavaScript’s s or dotAll flag changes that newline rule, though the cards do not provide a flag editor.
  • \d matches an ASCII digit in JavaScript, equivalent here to [0-9]; \D matches a non-digit.
  • \w matches ASCII letters, digits, and underscore; \W matches everything outside that set.
  • \s matches whitespace such as spaces, tabs, and newlines; \S matches non-whitespace.
  • [abc] matches one listed character, not the word “abc.”
  • [^abc] negates a set and matches one character not listed.
  • [a-z] expresses a range. Combine ranges as [A-Za-z0-9] when that exact ASCII policy is intended.

The backslash forms are easy to misread after they pass through a programming-language string. A regex literal for a digit in JavaScript can be /\d/; a JavaScript string passed to RegExp usually needs "\\d" so one backslash reaches the regex parser. JSON, shells, YAML, and HTML attributes add their own escaping rules. Always distinguish the regex itself from the container syntax.

Do not assume \w means every letter in every language. In JavaScript it remains centered on ASCII word characters, even with Unicode-aware matching. Property escapes such as \p{Letter} with the u flag address broader scripts but are outside the cards shown here.

Quantifiers answer “how many?”

A quantifier modifies the token or group immediately before it:

Syntax Meaning
* zero or more
+ one or more
? zero or one
{n} exactly n
{n,} at least n
{n,m} between n and m

ab+ means a followed by one or more b characters. It does not repeat the whole ab. To repeat the pair, group it: (?:ab)+.

Quantifiers are greedy by default and attempt the longest match that still allows the pattern to succeed. Add ? after a quantifier for lazy behavior, such as .*?, when supported. Lazy does not mean “fast” or “safe”; it means prefer fewer repetitions before expanding. The surrounding pattern still controls the final match.

Beware of zero-length possibilities. a* can match even where there is no a. Global iteration must advance after empty matches to avoid an infinite loop. The card implementation includes such a safety advance when collecting highlights.

Nested ambiguous quantifiers can cause severe backtracking in some engines. A pattern like (a+)+$ against an almost-matching long string is a classic risk. Keep alternatives distinct, anchor intended formats, bound repetition when practical, and use engine-specific timeouts or safer engines for untrusted input.

Anchors match positions, not characters

^ asserts the beginning of the string and $ the end. With JavaScript’s multiline m flag, they can also operate at line boundaries. The anchor cards demonstrate that mode with gm, while many other cards use g only. Read the mini pattern label on each card before generalizing its behavior.

\b is a word boundary between a \w and \W position, or an appropriate string edge; \B asserts the opposite. This is not a linguistic word-break algorithm. In cat category, \bcat\b isolates the standalone ASCII-style word, but non-Latin scripts and punctuation may behave differently from human expectations.

Anchors turn “contains” validation into whole-value validation. \d{4} can find four digits inside a longer string; ^\d{4}$ requires the entire single-line value to consist of four digits. In production validation, be explicit about line terminators and engine semantics rather than adding anchors mechanically.

Grouping, capture, and alternatives

Parentheses (abc) group tokens and create a numbered capture. Captures let replacement code or application logic retrieve a submatch. Non-capturing (?:abc) groups without adding a capture slot, which keeps numbering stable when extraction is unnecessary.

Alternation a|b chooses the left or right branch. Group it when shared context should apply to both:

^(cat|dog)s?$

This accepts cat, cats, dog, or dogs. Without grouping, anchor scope can surprise you. ^cat|dog$ means “starts with cat OR ends with dog,” not “the entire value is cat or dog.”

Capture numbering changes when a capturing group is inserted earlier. Named captures can make complex extraction more maintainable when the engine supports them. This cheat sheet focuses on foundational group syntax rather than replacement references, named groups, or backreferences.

Lookarounds assert context without consuming it

Positive lookahead (?=abc) requires following context. Negative lookahead (?!abc) rejects following context. Positive lookbehind (?<=abc) requires preceding context, while negative lookbehind (?<!abc) rejects it.

For example, \d+(?=px) matches the digits in 100px but not the px. The assertion verifies the unit without including it in the matched value. (?<=\$)\d+ can match digits immediately after a dollar sign without consuming the sign.

Lookbehind has historically varied more across engines and older runtimes than lookahead. Even where supported, variable-length lookbehind rules differ. If compatibility is broad, test the exact production versions or restructure the pattern using captures.

Because lookarounds are zero-width, their conditions do not move the current position. They are powerful for context, but several nested assertions can become harder to understand than a small parsing function.

How to learn from each card

Do not merely read the supplied example. Change one variable at a time:

  1. Type a string that should match and identify the highlighted span.
  2. Remove one required character and confirm the highlight disappears.
  3. Add a second candidate to observe the global g flag finding multiple matches.
  4. Insert spaces, punctuation, or a newline where boundaries might change.
  5. Copy the syntax token only after you can explain what it consumes or asserts.

The highlight panel marks complete matches, not capture groups. Asserted lookaround context remains unhighlighted because it is not consumed. Zero-width matches contain nothing visible, so pure assertions can be hard to visualize.

Editing affects only that card, not its fixed demo pattern or flags.

Build patterns from requirements, not snippets

Suppose the requirement is “an ASCII project code with three uppercase letters, a hyphen, and four digits.” Translate each clause:

^[A-Z]{3}-\d{4}$

The anchors require a whole-value match. [A-Z]{3} handles exactly three uppercase ASCII letters. The hyphen is literal outside a character set. \d{4} supplies four digits under JavaScript semantics.

Then list tests before deploying:

ABC-2048  accept
AB-2048   reject
abc-2048  reject
ABC-20481 reject
 ABC-2048 reject

Requirements still hide policy questions: whether lowercase, non-ASCII digits, surrounding whitespace, or empty values are accepted. Regex syntax cannot choose product rules.

Matching is not complete validation

A compact expression can verify surface shape, but it should not pretend to understand every domain. Dates require calendar checks after matching. Email addresses have extensive standards and operational constraints. URLs should use a URL parser. International phone numbers need numbering metadata. File paths and usernames depend on platform policy.

Use regex to find text, extract pieces, or enforce a limited grammar. Follow with parsing and business validation. Keep patterns readable and tested.

Never use a regex alone to sanitize input for SQL, HTML, shell commands, or file access. Use parameterized queries, contextual output encoding, argument arrays, and path APIs. Deny lists built from clever patterns routinely miss alternate representations.

Flags change the language of a pattern

The cards commonly demonstrate g for all matches and sometimes m for multiline anchors. JavaScript also provides flags such as i for case-insensitive matching, s for dotAll, u for Unicode-aware parsing, y for sticky matching, and d for match indices in supporting runtimes. Newer runtime features may add further behavior.

g does not make a pattern “more correct”; it changes iteration. Methods such as test on a reused global regex can be stateful because lastIndex advances. Reset or avoid sharing state when that matters. The cheat-sheet demos reset iteration before collecting highlights.

Case-insensitive behavior is not equivalent to lowercasing every language. Unicode and locale rules remain nuanced. Confirm with representative data.

Frequent debugging questions

Why does . not match a newline?

Dot excludes line terminators by default in JavaScript. Use the s flag or an explicit class appropriate to the target engine when matching across lines is intentional.

Why did [10] match one character instead of ten?

Square brackets define alternatives for one character, so [10] means 1 or 0. Use 10 for the literal sequence.

Is * the same as +?

No. * allows zero occurrences, while + requires at least one. That difference often determines whether empty input passes.

Why does my copied \d fail inside a string?

The host language may consume the backslash first. In a JavaScript string for new RegExp, write "\\d". Regex literals and other languages use different escaping.

Can the search box test my complete pattern?

No. It filters reference cards by their syntax, name, and description. The editable fields test each card’s fixed demonstration pattern against your sample text.

Are lookarounds supported everywhere?

Lookahead is widespread; lookbehind and advanced forms have more compatibility differences. Check the target engine and runtime version.

Why is a word boundary wrong for my language?

JavaScript \b relies on regex word-character semantics rather than full natural-language segmentation. Use Intl.Segmenter, Unicode-aware libraries, or language-specific tokenization when identifying human words.

Learn More

Read our comprehensive guide to master this utility.

Read Guide →