Complete Regex Cheat Sheet: Regular Expressions Syntax, Patterns & Examples
Master Regular Expressions with this ultimate Regex Cheat Sheet. Learn anchors, quantifiers, character classes, lookaheads, lookbehinds, flags, and copy-paste common regex patterns for email, URL, IP, phone, and password validation.
Regular Expressions (commonly known as Regex or RegEx) are powerful text-matching patterns used across virtually every programming language, shell script, log analyzer, and database query. Whether you are parsing server log files, validating user inputs in a frontend web form, executing complex search-and-replace refactoring in your IDE, or stripping raw HTML tags, having an authoritative Regex Cheat Sheet is an essential developer requirement.
This guide provides a comprehensive reference covering regular expression syntax, character classes, quantifiers, anchors, lookaround assertions, regex engine flags, performance optimizations, and a ready-to-use library of common copy-paste validation patterns.
1. Regex Flags & Global Modifiers Quick Reference
Regex flags change how pattern search algorithms operate across input strings. Flags are appended to the end of a regex expression (e.g. /pattern/gmi).
| Flag | Name | Description & Behavior |
|---|---|---|
| g | Global Match | Finds all matching instances in the string rather than stopping after the first match. |
| i | Case Insensitive | Ignores uppercase vs lowercase letter distinctions during pattern matching. |
| m | Multiline Mode | Causes anchors (^ and $) to match the start and end of each line, not just the entire string. |
| s | DotAll / Single Line | Allows the dot (.) wildcard character to match newline characters (\n, \r). |
| u | Unicode Support | Enables full Unicode code point processing, allowing UTF-16 surrogates and emojis to match. |
| y | Sticky Mode | Matches only from the exact target index indicated by the lastIndex property of the regex. |
2. Anchors & Boundary Assertions
Anchors do not consume characters in the target string. Instead, they assert zero-width position conditions where matching must occur.
| Symbol / Anchor | Boundary Type | Matching Condition |
|---|---|---|
| ^ | Start of String / Line | Matches the position immediately preceding the first character of string or line. |
| $ | End of String / Line | Matches the position immediately following the last character of string or line. |
| \b | Word Boundary | Matches position between a word character (\w) and a non-word character (\W). |
| \B | Non-Word Boundary | Matches any position where \b does not match (inside a word or between non-word chars). |
| \A | Start of Input (Absolute) | Matches absolute start of string input regardless of multiline flag setting. |
| \Z / \z | End of Input (Absolute) | Matches absolute end of string input regardless of multiline flag setting. |
3. Character Classes & Escape Sequences
Character classes define specific groups or ranges of characters that can match a single position.
| Sequence | Character Set | Equivalent Range / Meaning |
|---|---|---|
| . | Wildcard Dot | Matches any single character except line terminators (unless /s flag set). |
| \d | Digit | Matches any numeric digit [0-9]. |
| \D | Non-Digit | Matches any character that is NOT a numeric digit [^0-9]. |
| \w | Word Character | Matches alphanumeric characters and underscore [a-zA-Z0-9_]. |
| \W | Non-Word Character | Matches any character that is NOT an alphanumeric or underscore [^a-zA-Z0-9_]. |
| \s | Whitespace | Matches spaces, tabs, line breaks [ \t\n\r\f\v]. |
| \S | Non-Whitespace | Matches any non-whitespace character. |
| [abc] | Character List | Matches character 'a', 'b', or 'c'. |
| [^abc] | Negated List | Matches any character EXCEPT 'a', 'b', or 'c'. |
| [a-z] | Lower Character Range | Matches any lowercase letter from 'a' through 'z'. |
| [A-Z] | Upper Character Range | Matches any uppercase letter from 'A' through 'Z'. |
| [0-9] | Numeric Range | Matches any single digit from 0 through 9. |
4. Quantifiers: Greedy vs Lazy (Nondeterministic vs Deterministic)
Quantifiers specify how many times a character, group, or character class must repeat. By default, regular expressions are greedy — they attempt to match as many characters as possible.
| Quantifier | Match Count | Matching Strategy |
|---|---|---|
| * | 0 or more times | Greedy (matches maximum possible characters). |
| + | 1 or more times | Greedy (requires at least 1 match, grabs maximum). |
| ? | 0 or 1 time | Greedy (optional character assertion). |
| {n} | Exactly n times | Matches target token exactly n times. |
| {n,} | n or more times | Matches at least n times up to maximum available. |
| {n,m} | Between n and m | Matches minimum n times and maximum m times. |
| *? | 0 or more times | Lazy / Non-greedy (matches minimum possible characters). |
| +? | 1 or more times | Lazy / Non-greedy (stops at earliest possible match). |
| ?? | 0 or 1 time | Lazy optional match. |
Greedy vs Lazy Code Example
const htmlString = '<button class="btn">Submit</button><span>Cancel</span>';
// Greedy Pattern (.*) grabs everything from first '<' to LAST '>'
const greedyResult = htmlString.match(/<.*>/);
console.log(greedyResult[0]);
// Output: '<button class="btn">Submit</button><span>Cancel</span>'
// Lazy Pattern (.*?) stops at the FIRST '>'
const lazyResult = htmlString.match(/<.*?>/);
console.log(lazyResult[0]);
// Output: '<button class="btn">'5. Grouping, Capturing & Backreferences
Grouping constructs allow you to combine elements into single logical units for repetition operators, extract substring matches, or create named variables.
- (pattern) — Capturing Group: Groups sub-patterns together and stores match in numbered group memory ($1, $2, etc.).
- (?:pattern) — Non-Capturing Group: Groups sub-patterns together for quantifiers without allocating memory for capture groups.
- (?<name>pattern) — Named Capture Group: Assigns an explicit string identifier key to captured substring matches.
- \1, \2 — Backreference: References previous numbered capture groups within the same regex pattern string.
// Matching duplicate words using backreferences (\1)
const text = "The the quick brown fox fox jumped";
const duplicateWordRegex = /\b(\w+)\s+\1\b/gi;
console.log(text.match(duplicateWordRegex));
// Output: ['The the', 'fox fox']
// Named Capture Groups in ES2018+
const dateString = "2026-08-06";
const dateRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = dateRegex.exec(dateString);
console.log(match.groups.year); // '2026'
console.log(match.groups.month); // '08'
console.log(match.groups.day); // '06'6. Advanced Lookaround Assertions (Lookaheads & Lookbehinds)
Lookaround assertions allow you to match patterns based on what comes before or after a character without including that surrounding text in the captured match.
| Syntax | Assertion Name | Matching Logic |
|---|---|---|
| (?=pattern) | Positive Lookahead | Asserts that specified pattern MUST follow the current position. |
| (?!pattern) | Negative Lookahead | Asserts that specified pattern MUST NOT follow the current position. |
| (?<=pattern) | Positive Lookbehind | Asserts that specified pattern MUST precede the current position. |
| (?<!pattern) | Negative Lookbehind | Asserts that specified pattern MUST NOT precede the current position. |
// Positive Lookahead: Match dollar values (digits preceded by '$')
const priceText = "Items cost $49 and €99";
const dollars = priceText.match(/(?<=\$)\d+/g);
console.log(dollars); // ['49']
// Password Strength Validation with Lookaheads:
// Requires 1 Uppercase, 1 Lowercase, 1 Digit, Min 8 Chars
const strongPasswordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
console.log(strongPasswordRegex.test("SecurePass123")); // true7. Ready-to-Use Copy & Paste Regex Pattern Library
Here is a list of battle-tested, standard regex patterns commonly used in web application development.
1. Email Address Validation (RFC 5322 Standard)
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$2. URL / Web Address Validation (HTTP / HTTPS)
^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$3. IPv4 Address Matching
^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$4. Hexadecimal Color Code (#FFF or #FFFFFF)
^#?([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$5. US Phone Number (Formats: (123) 456-7890, 123-456-7890, 1234567890)
^^\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}$6. Slugification / URL Slugs (e.g. my-awesome-post-title)
^[a-z0-9]+(?:-[a-z0-9]+)*$7. HTML Tag Stripping Regex
<\/?[^>]+(>|$)8. Date Validation (ISO Format: YYYY-MM-DD)
^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01])$8. Language-Specific Regex Engine Differences
Different programming environments use different regular expression engines. Be aware of minor syntax variances:
| Language / Environment | Regex Engine | Key Capabilities & Gotchas |
|---|---|---|
| JavaScript (V8 / Node) | Built-in ECMAScript | Supports Lookaheads, Lookbehinds (ES2018+), Named Capture Groups, Unicode (/u). |
| Python (re module) | PCRE-like C Engine | Requires raw strings r'pattern'. Fixed-width lookbehinds only in standard re. |
| PHP (preg_* functions) | PCRE2 Library | Full feature set including atomic groups, possessive quantifiers, and recursion. |
| Go (regexp package) | RE2 Engine | Guarantees linear O(N) execution time by excluding lookarounds and backreferences. |
9. Test and Debug Regex Online with QuizOxa Tools
Need to test a regular expression against sample text, extract capture groups, or run fast search-and-replace transformations? Use the free QuizOxa Regex Tester tool.
QuizOxa performs 100% local pattern evaluation directly inside your browser using native JavaScript engines, ensuring your confidential strings and logs are never sent to external servers.
10. Frequently Asked Questions (FAQ)
What is the difference between greedy and lazy matching in regex?
Greedy matching (default, e.g., .*) expands to match as many characters as possible before completing the expression. Lazy matching (appending ?, e.g., .*?) stops matching at the first occurrence that satisfies the pattern.
Why is catastrophic backtracking dangerous in production regex?
Catastrophic backtracking happens when nested quantifiers (such as (a+)+) fail to match a string, forcing the regex engine to evaluate exponential (O(2^N)) permutations. This blocks the CPU event loop, causing ReDoS (Regular Expression Denial of Service) vulnerabilities.
How do non-capturing groups (?:...) improve performance?
Non-capturing groups group sub-expressions for quantifiers or alternation without storing match indices in memory array structures, reducing allocation overhead during matching.
Can I use lookbehinds in JavaScript?
Yes. Modern JavaScript engines (V8, JavaScriptCore, SpiderMonkey) added support for positive (?<=) and negative (?<! ) lookbehinds in ES2018.
11. Conclusion & Next Steps
Regular expressions are an essential tool for string parsing, input validation, and developer productivity. Bookmark this Regex Cheat Sheet and use QuizOxa Free Regex Tester to build and debug your expressions with real-time feedback.