CodeLiveStudio

Regex Cheat Sheet: Tokens, Examples and Explanations

Quick answer

This regex cheat sheet explains every common token with a real example: anchors (^, $, \b), character classes (\d, \w, \s), quantifiers (*, +, ?, {n,m}), groups and backreferences, lookarounds and flags. Every pattern can be pasted into the free regex tester to see live matches.

Reviewed by the CodeLive Studio team

Regular expressions are a dense little language: six punctuation marks can replace twenty lines of string parsing, but only if you remember what each symbol means. This cheat sheet is the reference we keep open while building the regex tools on this site. It is written for the JavaScript (ECMAScript) flavor, with notes where PCRE, Python or Go behave differently, and every pattern on the page runs live in the tester — no signup, nothing uploaded.

Regex dictionary: anchors and boundaries

Anchors do not match characters; they match positions. The most common regex bug is expecting ^ and $ to mean "start and end of the whole string" — in JavaScript they only do that without the m flag. With the multiline flag, they match at every line break instead, which is exactly what you want when scanning a log file line by line.

TokenMatchesExample
^Start of the string (start of each line with the m flag)^SELECT matches a query only at the beginning
$End of the string (end of each line with the m flag);$ matches a semicolon only at the end
\bWord boundary — between a \w and a non-\w character\bcat\b matches cat but not category
\BNot a word boundary — inside a word\Bcat matches category, scatter
.Any character except a line break (everything with the s flag)a.c matches abc, a-c, not a\nc

Python and PCRE also support \A (absolute string start) and \Z (absolute end); JavaScript does not — use ^ and $ without the m flag instead.

Regex dictionary: character classes

Character classes match one character out of a set. The shorthand classes (\d, \w, \s) are Unicode-aware in modern JavaScript only if you add the u flag; without it they are effectively ASCII. For digits with signs or decimals, combine classes rather than hoping one shorthand covers it.

TokenMatchesExample
\dOne digit, 0-9\d{4} matches 2026
\DOne character that is not a digit\D+ matches "Nov " in "Nov 5"
\wA word character: letter, digit or underscore\w+ matches hello_world
\WNot a word character (punctuation, spaces)\W matches -, !, @
\sAny whitespace: space, tab, newline, carriage returna\sb matches "a b"
\SNot whitespace\S+ matches any non-blank word
[abc]One character from the setb[ae]t matches bat, bet
[^abc]One character NOT in the set[^0-9] matches any non-digit
[a-z0-9]One character from the ranges[a-z0-9]{3} matches abc123 fragments

Regex dictionary: quantifiers (and why lazy matters)

Quantifiers repeat the previous token. The critical detail is greediness: a greedy quantifier grabs as much as it can, then walks back; a lazy quantifier (extra ?) takes as little as it can. When a pattern like <.+> swallows an entire HTML fragment instead of one tag, the fix is the lazy form <.+?>.

TokenMeaningExample
*0 or more times (greedy)ab*c matches ac, abc, abbc
+1 or more times (greedy)a+ matches aaa, not an empty string
?0 or 1 time — makes the token optionalcolou?r matches color, colour
{n}Exactly n times\d{3} matches 404
{n,}n or more times\d{2,} matches 99, 404, 2026
{n,m}Between n and m times\d{1,3} matches 8, 42, 255

Lazy versions (*?, +?, ??) share one idea: prefer the shortest match. <.+?> matches the single tag <b> inside "<b>hi</b>", where the greedy <.+> would swallow the whole string.

Regex new line: how to match line breaks correctly

The token \n matches a line feed, but real files usually end lines with a carriage return AND a line feed (\r\n on Windows, \n on Linux). The pattern \r?\n accepts both, which is why it is the safest way to split or match a new line in text copied from any operating system.

Matching "any character including the new line" is a different problem: the dot stops at \n by default. Two reliable fixes exist, and knowing both saves an hour of debugging.

  • /\r?\n/ — match or split a new line, Windows and Unix safe
  • /[\s\S]/ — "any character at all" in every regex flavor, no flags needed
  • /./s — same thing in JavaScript only, with the dotAll (s) flag
Line breaks: split, join and dot-all
"line1\r\nline2\nline3"
  .split(/\r?\n/);              // ["line1", "line2", "line3"]

"a\nb".match(/^a.b$/);          // null  (dot stops at \n)
"a\nb".match(/^a.b$/s);         // match (s = dotAll flag)
"a\nb".match(/a[\s\S]b/);       // match ([\s\S] = any char, any flavor)

Regex start of line: ^ with and without the multiline flag

This is the anchor question we see most. Without the m flag, ^ anchors to the very start of the string, so an ERROR at the top of a log matches but the same word mid-file does not. Add the m flag and ^ becomes "start of any line" — the pattern suddenly finds every error line, which is what people usually mean by a regex start-of-line match.

Anchoring to the start of a line
const log = "INFO boot\nERROR disk\nINFO ready";

log.match(/^ERROR/);        // null        (^ = string start)
log.match(/^ERROR/m);       // match       (m = every line start)
log.match(/^\w+$/gm);       // 3 matches   (each line, whole line)

Regex replace: capture groups and backreferences

A regex replace is where patterns earn their keep. Anything inside parentheses is a capture group; in the replacement string, $1, $2 … refer to the groups in order, and $& inserts the whole match. Named groups (?<year>\d{4}) make longer replacements readable — reference them as $<year> in JavaScript.

  • $1, $2 — first, second capture group in the replacement
  • $& — the entire matched text
  • $` and $' — text before and after the match
  • $<name> — a named group from (?<name>…)
Reordering a date with capture groups
"2026-10-23".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1");
// "23/10/2026"

"Ada Lovelace".replace(/(?<first>\w+) (?<last>\w+)/, "$<last>, $<first>");
// "Lovelace, Ada"

Regex lookaround: match next to something without consuming it

Lookaheads and lookbehinds assert what must be next to the match without including it in the result. The classic use is password rules: require a digit somewhere in the string without matching the digit itself. Lookbehind arrived in JavaScript with ES2018 and is safe in every current browser.

Lookahead and lookbehind
/(?=.*\d).{8,}/.test("abc12345");        // true (has a digit, 8+ chars)
"price: $42".match(/(?<=\$)\d+/);          // "42"  (the $ is not included)

// negative lookahead: words NOT followed by a comma
"a, b c".match(/\w+\b(?!,)/g);             // ["b", "c"]

Six ready-to-use patterns (copy, paste, test)

These are the patterns behind half of all quick data-extraction jobs. Each one is deliberately strict about boundaries so it does not match fragments inside longer strings, and each is safe to paste straight into the tester with sample text.

GoalPatternNotes
IPv4 address\b(?:\d{1,3}\.){3}\d{1,3}\bFinds 192.168.0.1 in any log line
ISO date\b\d{4}-\d{2}-\d{2}\bMatches 2026-10-23; validate ranges in code
URLhttps?:\/\/[^\s"')]+Stops at whitespace, quotes and brackets
Hex color#[0-9a-fA-F]{6}\bMatches #34d399, not #fff (use {3,6} for that)
HTML tag<\/?[a-z][a-z0-9]*\b[^>]*>Tag names only — parsing HTML with regex has limits
Time 24h\b(?:[01]\d|2[0-3]):[0-5]\d\bAccepts 09:41 and 23:59, rejects 24:00

The IPv4 pattern matches structure, not ranges: 999.999.999.999 passes. For validation (as opposed to extraction), add range checks in code.

How to test any pattern from this cheat sheet live

Reading a regex only gets you halfway; watching it match (or fail) on real text is what builds intuition. Open the regex tester, paste any pattern from this page with the sample flags, and you get live match highlighting, capture-group breakdowns and a replace preview as you type.

The tester runs the same ECMAScript engine as this cheat sheet describes, so flags, named groups and lookbehind behave exactly as documented here. Nothing is uploaded — the matching happens in your browser tab, which makes it safe for logs with sensitive lines in them.

Questions this guide answers

  • regex cheat sheet
  • regex new line
  • regex dictionary
  • regex start of line
  • regular expression replace
  • regex lookaround
  • online regex checker
  • regex generator

Frequently asked questions

What is the fastest way to learn regex from a cheat sheet?

Pick one row, write a three-line sample string, and test the pattern against it immediately. Every table on this page is ordered so each concept builds on the previous one — anchors, classes, quantifiers, groups, lookaround — and every pattern works in the regex tester without signup, so the read-then-run loop takes seconds.

How do I match a new line in regex?

Use \r?\n to match a line break on both Windows and Unix files. To make the dot match new lines too, either add the s (dotAll) flag or use [\s\S], which works in every regex flavor. Splitting a multi-line string into lines with .split(/\r?\n/) is the most common daily use.

Why does my ^ pattern only match the first line?

Without the m (multiline) flag, ^ anchors to the start of the whole string, not to each line. Add the m flag — /^ERROR/m — and ^ matches at the start of every line after a line break. The same applies to $ and line ends.

What is the difference between \d and [0-9]?

In JavaScript they are practically identical for ASCII text; both match one digit. Differences appear with Unicode digits in other scripts (\d can match those with the u flag) and in some other flavors where \d honors locale. For pure 0-9 matching, [0-9] is explicit and portable, which is why strict patterns tend to use it.

Which regex flavor does this cheat sheet use?

JavaScript (ECMAScript), which is what the on-site tester executes. The core tokens on this page — anchors, classes, quantifiers, groups, lookaround — are shared by PCRE, Python, Go and Java; the differences are noted inline, such as \A/\Z missing in JavaScript and lookbehind arriving in ES2018.

Can a regex generate patterns for me instead of me writing one?

That is the reverse problem — regex generators take sample text and propose a pattern, and they are handy for a first draft. A better habit for most people: build the pattern from this dictionary row by row, then test it live. You end up with a pattern you can actually read and maintain.