Regex Cheat Sheet
An interactive, searchable reference guide for regular expressions with inline pattern matching visualization.
Matches any single character except line terminators (newline).
/./gMatches any digit character (0-9). Equivalent to [0-9].
/\d/gMatches any character that is not a digit. Equivalent to [^0-9].
/\D/gMatches any alphanumeric character (letters, numbers) and underscore. Equivalent to [A-Za-z0-9_].
/\w/gMatches any character that is not a word character. Equivalent to [^A-Za-z0-9_].
/\W/gMatches any whitespace character (spaces, tabs, newlines).
/\s/gMatches any character that is not whitespace.
/\S/gMatches any single character listed inside the square brackets (a, b, or c).
/[cag]/gMatches any single character NOT listed inside the brackets.
/[^cat ]/gMatches a character within the specified range (in this case, lowercase a to z).
/[a-zA-Z]/gMatches the preceding token 0 or more times.
/ab*/gMatches the preceding token 1 or more times.
/ab+/gMatches the preceding token 0 or 1 time, making it optional.
/colou?r/gMatches the preceding token exactly n times.
/\b\d{3}\b/gMatches the preceding token n or more times.
/\b\d{3,}\b/gMatches the preceding token between n and m times.
/\b\d{2,4}\b/gMatches the start of the string, or the start of a line if multiline flag (m) is set.
/^hello/gmMatches the end of the string, or the end of a line if multiline flag (m) is set.
/\.[a-z]+$/gmMatches a position where a word character is adjacent to a non-word character (or start/end of string).
/\bcat\b/gMatches any position that is NOT a word boundary.
/\Bcat\B/gGroups multiple tokens together and creates a capture group for extracting substrings.
/(ha)/gGroups tokens without creating a separate capture group for extraction.
/(?:ha)/gMatches either the pattern on the left or the pattern on the right side of the pipe.
/cat|dog/gAsserts that the given pattern matches immediately after the current position, without consuming text.
/\d+(?=px)/gAsserts that the given pattern does NOT match immediately after the current position.
/\b\d+(?!px)\b/gAsserts that the given pattern matches immediately before the current position, without consuming text.
/(?<=\$)\d+/gAsserts that the given pattern does NOT match immediately before the current position.
/(?<!\$)\b\d+\b/gA 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’ssor dotAll flag changes that newline rule, though the cards do not provide a flag editor.\dmatches an ASCII digit in JavaScript, equivalent here to[0-9];\Dmatches a non-digit.\wmatches ASCII letters, digits, and underscore;\Wmatches everything outside that set.\smatches whitespace such as spaces, tabs, and newlines;\Smatches 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:
- Type a string that should match and identify the highlighted span.
- Remove one required character and confirm the highlight disappears.
- Add a second candidate to observe the global
gflag finding multiple matches. - Insert spaces, punctuation, or a newline where boundaries might change.
- 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.