Home › Guides › Developer › Regex cheat sheet with real-world patterns

Regex cheat sheet with real-world patterns

A practical regular expression cheat sheet with tested patterns for dates, prices, IP addresses and passwords, plus the mistakes to avoid.

By the tools4free.dev team · Last reviewed 4 December 2026

A regular expression (regex) is a compact pattern that describes a set of strings, used to search, validate and rewrite text. This guide covers the syntax you need most, then applies it to realistic tasks such as validating a date, pulling out prices and fixing whitespace. The examples use the JavaScript flavour, and every pattern shown here was tested before it was published. Other engines differ in small ways, which are noted below.

Cheat sheet

Characters and classes

PatternMatches
.Any character except a line break (with the s flag, line breaks too)
\d \DA digit 0-9 / anything but a digit
\w \WA letter, digit or underscore (ASCII) / the opposite
\s \SWhitespace (space, tab, newline) / non-whitespace
[abc] [^abc]One of a, b or c / any character except those
[a-z0-9]A character in either range
\. \$ \(A literal special character, escaped with a backslash

Anchors and boundaries

PatternMeaning
^ $Start and end of the input (of each line with the m flag)
\b \BA word boundary / not a word boundary

Quantifiers

PatternMeaning
* + ?0 or more, 1 or more, 0 or 1
{3} {2,5} {2,}Exactly 3, between 2 and 5, at least 2
*? +?Lazy versions: match as little as possible

Groups and lookaround

PatternMeaning
(abc)Capturing group, numbered from 1
(?<name>abc)Named capturing group
(?:abc)Non-capturing group
a|bAlternation: a or b
\1Backreference to group 1
(?=x) (?!x)Lookahead: followed by / not followed by x
(?<=x) (?<!x)Lookbehind: preceded by / not preceded by x

Common flags: g (find all matches), i (ignore case), m (multiline anchors), s (dot matches newline), u (Unicode mode).

Worked example 1: validating a date field

Goal: accept dates in YYYY-MM-DD form and reject obviously wrong months and days. A first attempt, ^\d{4}-\d{2}-\d{2}$, accepts 2026-13-45. Tighten each part:

const date = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;

date.exec('2026-12-04');  // ['2026-12-04', '2026', '12', '04']
date.exec('2026-13-45');  // null
date.exec('2026-02-31');  // matches, see below

The month alternation allows 01-09 or 10-12. The day allows 01-09, 10-29 or 30-31. Notice the last line: 2026-02-31 passes, because a regex does not know the calendar. Use the pattern to check the shape, then confirm the date with a date library. This is a theme: regex validates format, not meaning.

Worked example 2: extracting prices and rewriting text

Goal: pull every dollar amount out of free text, then reorder a name. Lookbehind lets you match the number without the symbol:

const text = 'cost $45.50 and $7';

text.match(/(?<=\$)\d+(?:\.\d\d)?/g);
// ['45.50', '7']

'John Smith'.replace(/(?<first>\w+) (?<last>\w+)/, '$<last>, $<first>');
// 'Smith, John'

'2026-12-04'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1');
// '04/12/2026'

In the price pattern, \$ is a literal dollar sign, \d+ is the whole-dollar part, and the optional group (?:\.\d\d)? adds exactly two decimal digits when present. In the replacement strings, $1 and $<name> insert captured text.

Reading a pattern step by step

When a pattern looks like noise, read it left to right and name each piece. Take ^(\d{4})-(0[1-9]|1[0-2])$, which checks a year and month such as 2026-12. The caret anchors the start. (\d{4}) captures exactly four digits. The hyphen is a literal. The second group offers two alternatives: a zero followed by 1-9, or a one followed by 0, 1 or 2. The dollar sign anchors the end, so nothing else may follow. Writing a pattern in the same way, one small part at a time, and testing each part before adding the next, finds mistakes far sooner than building a long pattern and wondering why it fails. If a pattern grows past a line or two, consider splitting the job into several simple checks, or use the x extended flag in engines that support it to add spaces and comments.

Handy patterns

TaskPatternNotes
Collapse whitespace\s+ replaced with a single spaceCombine with trim()
Trim both ends^\s+|\s+$ with the g flagOr use String.prototype.trim
Hex colour^#(?:[0-9a-f]{3}){1,2}$ with iAccepts 3 or 6 digits
Repeated word\b(\w+)\s+\1\b with giFinds "is is" in "This is is a test"
Strong password rule^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$Lookaheads each assert one rule
Number before a unit\d+(?=px)Matches 10 and 30 in "10px 20em 30px"
Username^[A-Za-z0-9_-]{3,16}$Length and characters in one pattern
IPv4 address^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$Rejects 999.1.1.1

Greedy and lazy matching

Quantifiers are greedy by default: they take as much as they can, then back off if the rest of the pattern fails. Against <b>x</b><b>y</b>, the pattern <b>.*<\/b> matches the whole string, while the lazy <b>.*?<\/b> stops at the first </b> and matches <b>x</b>. For HTML, though, do not use regex for anything more than a quick search. Nested and malformed markup defeats it, so use a real parser.

Differences between engines

Common mistakes

Frequently asked questions

What is the difference between * and +?

* allows zero repeats and + requires at least one. \d* matches an empty string, while \d+ does not.

How do I match a literal bracket or backslash?

Escape it with a backslash: \[, \(, \\. Inside a character class most characters are literal already, except ], \, ^ and -.

Why does my pattern work in one tool and not another?

The engines differ in escapes, lookbehind support and flag names. Check the documentation of the exact engine you are using.

Should I use regex to parse JSON or HTML?

No. Use JSON.parse or an HTML parser. Regex suits flat, regular text.

Try it: test any pattern against sample text, with live match highlighting, in the regex tester.

Sources