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
| Pattern | Matches |
|---|---|
. | Any character except a line break (with the s flag, line breaks too) |
\d \D | A digit 0-9 / anything but a digit |
\w \W | A letter, digit or underscore (ASCII) / the opposite |
\s \S | Whitespace (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
| Pattern | Meaning |
|---|---|
^ $ | Start and end of the input (of each line with the m flag) |
\b \B | A word boundary / not a word boundary |
Quantifiers
| Pattern | Meaning |
|---|---|
* + ? | 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
| Pattern | Meaning |
|---|---|
(abc) | Capturing group, numbered from 1 |
(?<name>abc) | Named capturing group |
(?:abc) | Non-capturing group |
a|b | Alternation: a or b |
\1 | Backreference 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
| Task | Pattern | Notes |
|---|---|---|
| Collapse whitespace | \s+ replaced with a single space | Combine with trim() |
| Trim both ends | ^\s+|\s+$ with the g flag | Or use String.prototype.trim |
| Hex colour | ^#(?:[0-9a-f]{3}){1,2}$ with i | Accepts 3 or 6 digits |
| Repeated word | \b(\w+)\s+\1\b with gi | Finds "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
- POSIX tools:
grepandseduse basic regular expressions by default, where+,?,|and()need backslashes. Usegrep -Efor extended syntax. POSIX has no\d, so write[0-9]or[[:digit:]]. - Lookbehind: supported in modern JavaScript, Python (fixed length only) and PCRE, but not in every engine.
- Named groups: JavaScript uses
(?<name>...). Python writes(?P<name>...). - Unicode: in JavaScript,
\wis ASCII only. Add theuflag and use\p{L}for any letter, so/^\p{Lu}/umatches the "É" in "Édith" while/^[A-Z]/does not.
Common mistakes
- Forgetting anchors. Without
^and$, a validation pattern matches anywhere in the input, so\d{3}accepts "abc1234". - Not escaping the dot.
example.comalso matches "exampleXcom". Writeexample\.com. - Trusting a loose IP pattern.
^(\d{1,3}\.){3}\d{1,3}$accepts999.1.1.1. Use the stricter pattern above, or parse the numbers. - Over-engineering email checks. A pattern like
^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$is a useful sanity check for typos, but it cannot prove an address exists. Send a confirmation message instead. - The global-flag trap. A
gregex keeps alastIndex, so calling.test()repeatedly on the same object alternates between true and false. Create a new regex or avoidgwhen you only test. - Catastrophic backtracking. Nested quantifiers such as
(a+)+bcan take exponential time on failing input. In a quick test,/^(a+)+b/against 26 letter a's followed by a "c" took roughly 0.8 seconds, and each extra character roughly doubles the time. Avoid nesting repeats of overlapping patterns and never run untrusted patterns on untrusted input. - Trailing punctuation in URLs.
https?:\/\/[^\s]+grabs the comma or full stop that follows a link in a sentence. Trim it afterwards.
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.