Reference with examples

Regex Cheat Sheet: syntax, flags and examples

Use this reference when you know what a pattern must do but cannot remember a symbol. Each operator has a concrete example. Test a complete expression rather than memorizing isolated characters.

Move from a symbol to a real example

This reference is for checking syntax, not for following a complete course. Explore pattern collections or practice solving tasks to apply operators confidently.

Character classes, quantities and assertions

ConceptRegexMeaningExample input
LiteralcatFinds exactly the sequence catcatfish
Any characterc.tThe dot consumes one character, usually except a newlinecat
Character class[aeiou]Exactly one vowele
Negated class[^0-9]One non-digitA
Digit\dA digit in the active engine5
Word character\wUsually an ASCII letter, digit, or underscore in JavaScript_
Whitespace\sWhitespace such as a space or tab
Optionalcolou?rThe preceding character can occur zero or oncecolor
One or more\d+One or more digits123
Zero or moreab*cZero or more b charactersac
Exact count[A-Z]{2}Exactly two uppercase lettersBA
Range\d{2,4}Between two and four digits123
Start^AA at the start of the input (or line with m)Apple
Endend$end at the end of the input (or line with m)the end
Noncapturing(?:cat|dog)Group alternatives without an extra capturedog
Named group(?<code>[A-Z]{2})Capture a named value (JavaScript syntax)BA
Positive lookahead\d+(?= kg)Match number only before kg12 kg
Positive lookbehind(?<=ID:)\d+Match digits only after ID:ID:42
Escaped dot\.Match an actual dot, not any character.
Alternationcat|dogMatch either alternativecat

Examples describe JavaScript Regex. Other engines differ in Unicode classes, escape rules, lookbehind support and named-group syntax.

Flags in JavaScript

FlagWhen to use it
gFind all occurrences in a string, not just the first.
iIgnore case when uppercase and lowercase mean the same thing.
mTreat ^ and $ as line boundaries.
sLet the dot match newline characters.
uUse Unicode-aware pattern behavior; required for properties such as \p{L}.

Six ready-to-test patterns

Run these examples and then deliberately alter a sample to discover a false positive. A format match does not prove an email exists or that a postal code is assigned.

Debugging three common mistakes

  1. Using . as a literal period: file.txt also matches fileXtxt. Write file\.txt.
  2. Forgetting anchors: \d{5} finds five digits inside longer strings. Use ^\d{5}$ for a whole five-digit value.
  3. Using .* for a known format: define explicit character classes and lengths, then test rejection cases.

Practice method: write one valid case, one invalid case, choose a small pattern, then improve only after finding a counterexample.

Debugging practice

Practice with eight documented mistakes and four realistic developer workflows. Compare the broken pattern, the fix, and negative test cases before you reuse a solution.

Open the debugging lab