QuizOxa Tools
Back to all articles
General August 6, 2026 20 min read QuizOxa Team

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).

FlagNameDescription & Behavior
gGlobal MatchFinds all matching instances in the string rather than stopping after the first match.
iCase InsensitiveIgnores uppercase vs lowercase letter distinctions during pattern matching.
mMultiline ModeCauses anchors (^ and $) to match the start and end of each line, not just the entire string.
sDotAll / Single LineAllows the dot (.) wildcard character to match newline characters (\n, \r).
uUnicode SupportEnables full Unicode code point processing, allowing UTF-16 surrogates and emojis to match.
ySticky ModeMatches 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 / AnchorBoundary TypeMatching Condition
^Start of String / LineMatches the position immediately preceding the first character of string or line.
$End of String / LineMatches the position immediately following the last character of string or line.
\bWord BoundaryMatches position between a word character (\w) and a non-word character (\W).
\BNon-Word BoundaryMatches any position where \b does not match (inside a word or between non-word chars).
\AStart of Input (Absolute)Matches absolute start of string input regardless of multiline flag setting.
\Z / \zEnd 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.

SequenceCharacter SetEquivalent Range / Meaning
.Wildcard DotMatches any single character except line terminators (unless /s flag set).
\dDigitMatches any numeric digit [0-9].
\DNon-DigitMatches any character that is NOT a numeric digit [^0-9].
\wWord CharacterMatches alphanumeric characters and underscore [a-zA-Z0-9_].
\WNon-Word CharacterMatches any character that is NOT an alphanumeric or underscore [^a-zA-Z0-9_].
\sWhitespaceMatches spaces, tabs, line breaks [ \t\n\r\f\v].
\SNon-WhitespaceMatches any non-whitespace character.
[abc]Character ListMatches character 'a', 'b', or 'c'.
[^abc]Negated ListMatches any character EXCEPT 'a', 'b', or 'c'.
[a-z]Lower Character RangeMatches any lowercase letter from 'a' through 'z'.
[A-Z]Upper Character RangeMatches any uppercase letter from 'A' through 'Z'.
[0-9]Numeric RangeMatches 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.

QuantifierMatch CountMatching Strategy
*0 or more timesGreedy (matches maximum possible characters).
+1 or more timesGreedy (requires at least 1 match, grabs maximum).
?0 or 1 timeGreedy (optional character assertion).
{n}Exactly n timesMatches target token exactly n times.
{n,}n or more timesMatches at least n times up to maximum available.
{n,m}Between n and mMatches minimum n times and maximum m times.
*?0 or more timesLazy / Non-greedy (matches minimum possible characters).
+?1 or more timesLazy / Non-greedy (stops at earliest possible match).
??0 or 1 timeLazy optional match.

Greedy vs Lazy Code Example

javascriptread-only snippet
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.
javascriptread-only snippet
// 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.

SyntaxAssertion NameMatching Logic
(?=pattern)Positive LookaheadAsserts that specified pattern MUST follow the current position.
(?!pattern)Negative LookaheadAsserts that specified pattern MUST NOT follow the current position.
(?<=pattern)Positive LookbehindAsserts that specified pattern MUST precede the current position.
(?<!pattern)Negative LookbehindAsserts that specified pattern MUST NOT precede the current position.
javascriptread-only snippet
// 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")); // true

7. 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)

regexread-only snippet
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

2. URL / Web Address Validation (HTTP / HTTPS)

regexread-only snippet
^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$

3. IPv4 Address Matching

regexread-only snippet
^(?:(?: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)

regexread-only snippet
^#?([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$

5. US Phone Number (Formats: (123) 456-7890, 123-456-7890, 1234567890)

regexread-only snippet
^^\+?\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)

regexread-only snippet
^[a-z0-9]+(?:-[a-z0-9]+)*$

7. HTML Tag Stripping Regex

regexread-only snippet
<\/?[^>]+(>|$)

8. Date Validation (ISO Format: YYYY-MM-DD)

regexread-only snippet
^\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 / EnvironmentRegex EngineKey Capabilities & Gotchas
JavaScript (V8 / Node)Built-in ECMAScriptSupports Lookaheads, Lookbehinds (ES2018+), Named Capture Groups, Unicode (/u).
Python (re module)PCRE-like C EngineRequires raw strings r'pattern'. Fixed-width lookbehinds only in standard re.
PHP (preg_* functions)PCRE2 LibraryFull feature set including atomic groups, possessive quantifiers, and recursion.
Go (regexp package)RE2 EngineGuarantees 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.