Regex Cheat Sheet: Syntax, Common Patterns & Examples
Introduction
Regular expressions (regex) are essential for input validation, log parsing, data extraction, and bulk search-and-replace workflows across every programming language. But because regex syntax is compact and symbolic, having a quick, dependable reference saves hours of trial and error.
This regex cheat sheet provides a fast syntax reference, character classes, quantifiers, lookarounds, flags, and battle-tested patterns for common developer tasks like email, URL, UUID v4, date, and number matching.
All examples use standard ECMAScript / JavaScript regular expression syntax. You can test and inspect any pattern in real time with our free, browser-based Regex Tester.
Tested Regex Pattern Library
The Regex Tester includes a searchable pattern library for common developer tasks. Each entry shows the JavaScript expression, a matching input, a non-matching input, and limitations worth knowing before using it in production.
Useful starting points include:
- Validation: email addresses, hexadecimal colors, integers, decimals, slugs, and alphanumeric values.
- Networking: IPv4, fully expanded IPv6, hostnames, MAC addresses, and ports.
- Dates and times: ISO-style dates, 24-hour times, ISO date-times, and simple durations.
- Programming: JavaScript-style identifiers, semantic versions, JSON string tokens, Base64, and log levels.
- Text processing: whitespace, duplicate spaces, quoted strings, HTML-like tags, and CSV fields.
These patterns are intentionally practical rather than universal parsers. For example, a URL expression cannot prove that a website exists, and a tag-shaped expression must not be used to parse nested HTML. Select Test Pattern in the library to load an example into the tester, then adjust the expression and flags for your input.
Regex Syntax Cheat Sheet
Test your expressions live: Run any pattern below in our free Regex Tester with real-time match highlighting, flag toggling, and replace previewing.
| Token | Meaning / Description | Example | Matches |
|---|---|---|---|
. | Any character except line breaks (\n, \r) | c.t | cat, cot, c9t |
^ | Start of string (or start of line in multiline mode) | ^Hello | Hello at beginning |
$ | End of string (or end of line in multiline mode) | World$ | World at end |
* | 0 or more occurrences of previous item (greedy) | ab*c | ac, abc, abbbc |
+ | 1 or more occurrences of previous item (greedy) | ab+c | abc, abbbc (not ac) |
? | 0 or 1 occurrence of previous item (optional) | colou?r | color, colour |
{n} | Exactly n occurrences of previous item | \d{4} | 2026, 1999 |
{n,} | n or more occurrences of previous item | \d{2,} | 12, 456, 98765 |
{n,m} | Between n and m occurrences (inclusive) | \d{2,4} | 12, 123, 1234 |
[...] | Character class: matches any single character in set | [aeiou] | a, e, i, o, or u |
[^...] | Negated class: matches any character NOT in set | [^0-9] | Any non-digit character |
(...) | Capturing group: groups tokens & captures match | (\d{3}) | Saves 3 digits as $1 |
(?:...) | Non-capturing group: groups without saving capture | (?:https?://) | Groups for quantifier without saving |
| | Alternation: matches expression before OR after | | cat|dog | cat or dog |
\ | Escape character: removes special meaning of token | \. | Literal period . |
\d | Any digit; shorthand for [0-9] | \d+ | 42, 100 |
\D | Any non-digit; shorthand for [^0-9] | \D | A, !, space |
\w | Word character: letters, digits, underscore [a-zA-Z0-9_] | \w+ | user_42, hello |
\W | Non-word character: [^a-zA-Z0-9_] | \W | -, @, . |
\s | Whitespace character: space, tab (\t), newline (\n, \r) | \s+ | Spaces or line breaks |
\S | Non-whitespace character: [^\s] | \S+ | Any sequence without spaces |
\b | Word boundary: position between \w and \W | \bcat\b | cat in "a cat sat" (not in "catalog") |
\B | Non-word boundary: position where both sides are word chars | \Bcat | Matches cat inside scatter |
Regex Character Classes
Character classes match a single character from a specified set or range, enclosed within square brackets [...].
Common Ranges
[a-z] # Matches any lowercase ASCII letter (a through z)
[A-Z] # Matches any uppercase ASCII letter (A through Z)
[0-9] # Matches any single digit (0 through 9)
[a-zA-Z0-9] # Alphanumeric: lowercase, uppercase, or digit
[0-9a-fA-F] # Hexadecimal digit (0-9, a-f, A-F)
[^0-9] # Negated class: matches anything that is NOT a digit
Character Class Shorthands
\dvs[0-9]: In standard ASCII environments,\dmatches any single digit from 0 to 9.\wvs[a-zA-Z0-9_]: Note that\wincludes the underscore_. If your validation rule forbids underscores (such as standard subdomain or hostname rules), use[a-zA-Z0-9].\s: Matches spaces, tabs (\t), carriage returns (\r), line feeds (\n), and form feeds (\f).
Important Rules Inside Character Classes
Special characters behave differently inside [...]:
[.]matches a literal dot without needing an escape backslash.[*+?]matches literal asterisks, pluses, or question marks.- The hyphen
-denotes a range when between two characters (a-z), but acts as a literal hyphen if placed first ([-az]), last ([az-]), or escaped ([a\-z]). - The caret
^negates the entire class only when it is the very first character after[(e.g.,[^abc]). If placed elsewhere in the class ([a^bc]), it matches a literal caret.
Regex Quantifiers: Greedy vs Lazy Matching
Quantifiers specify how many times a token, character class, or group must appear:
* # 0 or more occurrences (greedy)
+ # 1 or more occurrences (greedy)
? # 0 or 1 occurrence (optional)
{3} # Exactly 3 occurrences
{3,} # 3 or more occurrences
{3,6} # Between 3 and 6 occurrences (inclusive)
Understanding Greedy vs. Lazy Matching
By default, quantifiers are greedy: they swallow as much text as possible while still allowing the rest of the pattern to match.
const html = "<div>First</div><div>Second</div>";
// Greedy matching: (.*) consumes everything from the first <div> to the final </div>
const greedy = html.match(/<div>.*<\/div>/);
console.log(greedy[0]);
// Output: "<div>First</div><div>Second</div>"
To make a quantifier lazy (non-greedy), append a question mark ?. A lazy quantifier stops at the first valid delimiter that satisfies the expression:
// Lazy matching: (.*?) stops at the very first closing </div>
const lazy = html.match(/<div>.*?<\/div>/);
console.log(lazy[0]);
// Output: "<div>First</div>"
Summary Comparison: * vs + vs ?
| Pattern | Target: "http" | Target: "https" | Target: "htt" | Target: "httpsss" | Rule Summary |
|---|---|---|---|---|---|
https? | ✅ Match | ✅ Match | ❌ No match | ❌ No match | s is optional (0 or 1 time) |
https* | ✅ Match | ✅ Match | ❌ No match | ✅ Match | s can appear 0, 1, or many times |
https+ | ❌ No match | ✅ Match | ❌ No match | ✅ Match | s must appear at least 1 time |
Regex Anchors and Boundaries
Anchors assert a position within a string without consuming any characters.
Start ^ and End $ Anchors
Omitting anchors is a common cause of input-validation bugs. Without anchors, a regex matches any substring:
const patternWithoutAnchors = /\d{5}/;
patternWithoutAnchors.test("order_12345_details"); // true! Matches substring "12345"
const patternWithAnchors = /^\d{5}$/;
patternWithAnchors.test("order_12345_details"); // false! Entire string must be 5 digits
patternWithAnchors.test("12345"); // true
^: Asserts the position immediately before the first character.$: Asserts the position immediately after the last character.
Word Boundaries: \b and \B
Word boundaries match the boundary between a word character (\w) and a non-word character (\W) or the string edges:
const text = "A cat sat on the catalog.";
// \b ensures we match the standalone word "cat", not "cat" inside "catalog"
const matches = text.match(/\bcat\b/g);
console.log(matches); // ["cat"]
// \B matches where both surrounding characters are word characters
const insideCat = "scatter".match(/\Bcat/);
console.log(insideCat !== null); // true
Groups, Alternation, and Lookarounds
Grouping allows you to apply quantifiers to multiple tokens, isolate values for extraction, or branch between alternatives.
1. Capturing Groups: (...)
Capturing groups store matched substrings in memory so you can refer back to them programmatically or in replacement strings:
const date = "2026-09-22";
const match = date.match(/^(\d{4})-(\d{2})-(\d{2})$/);
if (match) {
const [, year, month, day] = match;
console.log(`Year: ${year}, Month: ${month}, Day: ${day}`);
// Year: 2026, Month: 09, Day: 22
}
// Convert YYYY-MM-DD to DD/MM/YYYY using replacement tokens
const formatted = date.replace(/^(\d{4})-(\d{2})-(\d{2})$/, "$3/$2/$1");
console.log(formatted); // "22/09/2026"
2. Non-Capturing Groups: (?:...)
When you need to group tokens for a quantifier or alternation but do not need to store the matched value, use a non-capturing group. This improves execution performance and prevents polluting replacement slots:
^(?:https?|ftp)://[^\s/$.?#].[^\s]*$
3. Alternation: |
The pipe character | acts as a logical OR:
\b(?:cat|dog|fish)\b
Always wrap alternations in groups when combined with other tokens; otherwise, ^cat|dog$ matches strings starting with cat OR ending with dog.
4. Backreferences: \1, \2
Backreferences match the exact text previously captured by an earlier group:
// Match repeated duplicate words like "the the"
const duplicateWords = /\b(\w+)\s+\1\b/i;
console.log(duplicateWords.test("Paris in the the spring")); // true
5. Lookahead Assertions
Lookaheads inspect what follows the current position without consuming characters:
- Positive Lookahead
(?=...): Asserts that the pattern inside matches immediately after:\d+(?=px) # Matches "100" in "100px", but not "100em" - Negative Lookahead
(?!...): Asserts that the pattern inside does NOT match immediately after:\d+(?!px) # Matches "100" in "100em", but not "100px"
6. Lookbehind Assertions (ES2018+)
Lookbehinds inspect what precedes the current position without consuming characters:
- Positive Lookbehind
(?<=...): Asserts that the pattern matches immediately before:(?<=\$)\d+ # Matches "50" in "$50", but not "€50" - Negative Lookbehind
(?<!...): Asserts that the pattern does NOT match immediately before:(?<!\$)\d+ # Matches "50" in "50 miles", but not "$50"
Note on Lookbehind Support: Modern browsers, Node.js (8.10+), Bun, and Deno fully support lookbehinds. Avoid lookbehinds if targeting legacy environments like Internet Explorer or early Safari versions (pre-Safari 16.4).
JavaScript Regex Flags
Flags modify how the regular expression engine searches strings. In JavaScript, declare flags after the closing slash (/pattern/flags) or pass them as the second parameter to new RegExp("pattern", "flags").
| Flag | Name | Function / Description | Practical Example |
|---|---|---|---|
g | Global | Finds all matches throughout the text rather than stopping after the first match. | "test test".replace(/test/g, "ok") |
i | Case-insensitive | Matches letters regardless of uppercase or lowercase. | /[a-z]/i matches "A" and "a" |
m | Multiline | Modifies ^ and $ to match the beginning and end of each line (\n). | Multi-line log parsing |
s | DotAll | Allows the dot . metacharacter to match newline characters (\n, \r). | Matching across multi-line HTML tags |
u | Unicode | Enables full Unicode compliance; correctly handles surrogate pairs and emojis. | /\p{Emoji}/u |
y | Sticky | Matches only at the index specified by the lastIndex property of the RegExp object. | High-performance lexical parsers |
// Combining flags: global + case-insensitive
const regex = /error/gi;
const log = "ERROR: Connection timeout. Error: Retry scheduled.";
const matches = log.match(regex);
console.log(matches); // ["ERROR", "Error"]
Common Regex Patterns
Here is a curated collection of production-ready regular expressions for typical developer requirements. Each pattern includes an explanation, examples, and limitations.
Tip: You can test, modify, and debug any of these expressions directly in our free Regex Tester.
1. Email Validation Regex
Validating email addresses with regular expressions is notoriously nuanced because the official specification (RFC 5322) allows archaic quoted strings, comments, and IP literals. In real-world web applications, an overly complex RFC regex is brittle and difficult to maintain.
For practical web development, use a clean format validation pattern:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Breakdown
^[a-zA-Z0-9._%+-]+: Username allows alphanumeric characters, dots, underscores, percent signs, pluses, and hyphens.@: Mandatory at-sign.[a-zA-Z0-9.-]+: Domain name with subdomains and hyphens.\.[a-zA-Z]{2,}$: Top-level domain (TLD) of at least 2 characters.
Limitations
This regex verifies that an address is structurally well-formed. It cannot confirm that the domain has active DNS MX records, that the inbox exists, or that mail will be accepted. For user onboarding, combine format checking with an email verification confirmation link.
2. URL Regex Pattern
Matching and validating web URLs requires handling transfer schemes (http vs https), subdomains, port numbers, paths, and query strings:
^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)$
Breakdown
^https?:\/\/: Requireshttp://orhttps://.(?:www\.)?: Optionally matches thewww.subdomain without capturing it.[-a-zA-Z0-9@:%._\+~#=]{1,256}: Validates host labels up to 256 characters.\.[a-zA-Z0-9()]{1,6}\b: Matches the domain extension.(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*): Matches paths, query parameters, and URL fragments.
Practical Note
If you need to encode or decode query parameters extracted via regex, use our browser-based URL Encoder / Decoder to inspect percent-encoded values safely.
3. IPv4 Address Regex
An IPv4 address consists of four 8-bit octets separated by dots, where each decimal value ranges strictly from 0 to 255:
^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$
Breakdown of Each Octet (25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d):
25[0-5]: Numbers from 250 through 255.2[0-4]\d: Numbers from 200 through 249.1\d\d: Numbers from 100 through 199.[1-9]?\d: Numbers from 0 through 99 (disallowing leading zeros like01).
Limitations
This regex strictly checks IPv4 addresses. It does not match IPv6 addresses (which use colons, hexadecimal values, and double-colon compression like 2001:db8::1). Always validate IPv4 and IPv6 independently when handling dual-stack network traffic.
4. UUID v4 Validation Regex
Universally Unique Identifiers (UUIDs) following the RFC 4122 specification contain 32 hexadecimal characters formatted in five hyphen-separated blocks (8-4-4-4-12).
For UUID Version 4 (random generation), the version digit must be 4 and the variant digit must be 8, 9, a, or b:
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
Breakdown
^[0-9a-f]{8}-: 8 hexadecimal characters.[0-9a-f]{4}-: 4 hexadecimal characters.4[0-9a-f]{3}-: Version 4 indicator (first character must be4).[89ab][0-9a-f]{3}-: Variant 1 indicator (first character must be8,9,a, orb).[0-9a-f]{12}$: Final 12 hexadecimal characters./i: Case-insensitive flag to accept uppercase hex letters.
To generate cryptographically secure UUID v4 strings in bulk, use our free UUID Generator, or read our comprehensive guide on What is a UUID?.
5. Date Format Regex (YYYY-MM-DD)
To validate standard ISO-8601 calendar date formats:
^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$
Breakdown
^\d{4}: Four-digit year.-(?:0[1-9]|1[0-2]): Month from01through12.-(?:0[1-9]|[12]\d|3[01])$: Day from01through31.
Critical Caveat: Format vs Calendar Validity
A regular expression validates syntactic format, not true calendar validity. For example, the string 2026-02-31 or 2025-02-29 (a non-leap year) will successfully match this regex because 31 and 29 are within the valid day range. Always pass the extracted year, month, and day into language-level date constructors (such as JavaScript's new Date()) to verify actual calendar dates.
6. Username Regex
Usernames generally require alphanumeric characters, optional hyphens or underscores, and a constrained length:
^[a-zA-Z0-9](?:[a-zA-Z0-9_-]{1,18}[a-zA-Z0-9])?$
Breakdown
^[a-zA-Z0-9]: Must begin with an alphanumeric character (disallows leading-or_).(?:[a-zA-Z0-9_-]{1,18}[a-zA-Z0-9])?$: Allows 1 to 18 middle characters (including-and_) and requires the final character to be alphanumeric. Enforces a total length of 1 to 20 characters with no trailing punctuation.
Examples Matched
john_doe(Valid)dev-toolkit(Valid)_admin(Rejected: starts with underscore)admin-(Rejected: ends with hyphen)
7. Password Policy Regex
Many web applications enforce baseline password complexity rules (e.g., minimum 8 characters, at least one uppercase letter, one lowercase letter, one digit, and one special symbol) using positive lookaheads:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Breakdown
^: Start of string.(?=.*[a-z]): Asserts at least one lowercase character exists.(?=.*[A-Z]): Asserts at least one uppercase character exists.(?=.*\d): Asserts at least one numeric digit exists.(?=.*[@$!%*?&]): Asserts at least one allowed special symbol exists.[A-Za-z\d@$!%*?&]{8,}$: Enforces allowed character set and minimum 8-character length.
Security Note
A regular expression validates adherence to a mechanical password policy; it does not evaluate entropy or guarantee that a password is safe from credential stuffing. Passwords like Password123! satisfy this regex but are easily cracked. Modern security standards (such as NIST SP 800-63B) favor passphrase length and breached-password checks over complex character composition rules.
8. Whitespace and Empty String Patterns
Detecting empty strings or strings containing only whitespace:
^\s*$
To collapse multiple redundant spaces into a single space in JavaScript:
const messy = "Hello world! How are you?";
const cleaned = messy.replace(/\s+/g, " ");
console.log(cleaned); // "Hello world! How are you?"
To trim leading and trailing whitespace manually:
^\s+|\s+$
9. Number and Decimal Regex Patterns
Positive and Negative Integers
^-?\d+$
Matches 42, -17, and 0.
Decimals with Optional Sign
^-?\d+(?:\.\d+)?$
Matches 3.14, -0.05, and 100.
Two-Decimal Currency / Monetary Values
^\d+\.\d{2}$
Matches 19.99 and 0.50, but rejects 19.9 and 19.999.
Positive Numbers Only (No Negative Sign)
^\d+(?:\.\d+)?$
Matches 0, 42, 12.5.
10. URL Slug Regex
URL slugs in modern web routing (like blog article slugs) consist of lowercase alphanumeric words delimited by single hyphens:
^[a-z0-9]+(?:-[a-z0-9]+)*$
Breakdown
^[a-z0-9]+: Must begin with lowercase letters or digits.(?:-[a-z0-9]+)*$: Subsequent words must be preceded by a single hyphen. Disallows leading hyphens (-slug), trailing hyphens (slug-), and consecutive hyphens (slug--name).
11. Hex Color Codes
Matching 3-digit shorthand or 6-digit standard hexadecimal color values (such as #fff or #1e293b):
^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
Breakdown
^#: Requires a leading hash symbol#.([0-9a-fA-F]{3}|[0-9a-fA-F]{6}): Matches either exactly 3 hexadecimal characters (#fff) or exactly 6 hexadecimal characters (#ffffff), case-insensitively.$: End of string.
12. International Phone Numbers
Phone numbers vary across international numbering plans (such as ITU-T E.164). The following pattern accommodates international prefixes with optional country codes, spaces, parentheses, and hyphens:
^\+?[1-9]\d{0,2}[-.\s]?\(?\d{1,4}\)?[-.\s]?\d{1,4}[-.\s]?\d{1,9}$
Matched Examples
+1 (555) 123-4567+44 20 7946 0958+6012-34567891234567890
Limitations
This regex verifies that an input resembles a plausible phone number format. It cannot verify whether an area code exists or if the line is active. For SMS verification, use a dedicated library such as Google's libphonenumber.
Testing and Debugging Regular Expressions
Developing regular expressions without interactive feedback often leads to silent syntax bugs, unexpected match failures, or performance degradation. When writing regex for production:
- Test against edge cases: Test both valid inputs and malformed strings (e.g., trailing whitespace, missing subdomains, uppercase variations).
- Prevent Catastrophic Backtracking (ReDoS): Avoid nesting quantifiers on overlapping expressions (such as
(a+)+$), which causes exponential CPU evaluation times on non-matching inputs. - Verify capture group indices: When writing substitution patterns with
$1and$2, verify whether each group is capturing(...)or non-capturing(?:...).
A practical regex validation workflow
For a reliable validator, start with the exact input rules rather than trying to match every possible case:
- Define whether the entire string must match; add
^and$when it does. - Write the smallest readable pattern that matches valid examples.
- Add invalid examples, empty values, whitespace, Unicode, and boundary lengths.
- Test the pattern in the target engine because JavaScript, Python, and PCRE do not support exactly the same features.
- Keep user input bounded and avoid nested overlapping quantifiers that can cause excessive backtracking.
Use the DevToolkit Regex Tester to test a pattern interactively, then compare the syntax with this regex cheat sheet while refining it.
Frequently Asked Questions (FAQ)
What is a regular expression (regex)?
A regular expression is a sequence of characters that defines a search pattern. It is used in programming languages, text editors, and command-line tools for pattern matching, string validation, data extraction, and search-and-replace operations.
What does .* mean in regex?
In regular expressions, the dot (.) matches any character except line breaks, and the asterisk () is a quantifier meaning zero or more times. Combined, '.' matches any sequence of characters of any length. By default it is greedy, matching as much text as possible.
What is the difference between * and + in regex?
The asterisk (*) matches zero or more occurrences of the preceding element, meaning the element is optional. The plus sign (+) requires one or more occurrences, meaning the element must appear at least once.
What do the ^ and $ anchors mean in regex?
The caret (^) asserts the start of a string (or line in multiline mode), while the dollar sign ($) asserts the end of a string. Using both anchors (^pattern$) ensures the entire string matches rather than just a substring.
How do I make a regular expression case-insensitive?
Add the 'i' flag after the closing regex delimiter (e.g., /pattern/i in JavaScript, or re.IGNORECASE in Python). This allows letters like 'a' and 'A' to match interchangeably.
What is the difference between capturing and non-capturing groups?
A capturing group (pattern) isolates and stores the matched substring in memory for backreferences and replacements ($1, $2). A non-capturing group (?:pattern) groups sub-expressions for quantifiers or alternation without storing the match or consuming capture slots.
Test Your Patterns Live in DevToolkit
Have a pattern you want to verify or debug? Test it against custom inputs, toggle flags, inspect live highlight captures, and evaluate replacements with the DevToolkit Regex Tester. Everything runs 100% locally in your browser using the native JavaScript engine with zero latency and complete privacy.