Free RegEx Tester & Pattern Explainer Online (Real-Time PCRE & JS)

100% Client-Side Privacy

Regular Expression (RegEx) Tester & Explainer

Test, debug, and benchmark PCRE and JavaScript regular expressions in real time. Inspect match groups, test edge cases, and eliminate catastrophic backtracking vulnerabilities.

/ /
Test String / Target Text 0 chars
Match Results & Capture Groups 0 matches
Matches will appear here automatically…
Ready. Enter pattern and test string.
Execution: 0.00ms
Compiler & Pattern Matching Audit: Verified by Mamun Hossain, Systems Architect. Built strictly in compliance with ECMAScript RegExp specifications and PCRE2 standards with ReDoS vulnerability analysis.

Understanding Regular Expression Grammar & Quantifiers

Regular expressions (RegEx) provide declarative pattern-matching syntax across string buffers. Modern engines leverage three primary syntactic constructs:

  • Character Classes: \d (digits 0-9), \w (alphanumeric and underscore), \s (whitespace characters), [^abc] (negated character class).
  • Anchors & Boundaries: ^ (start of line), $ (end of line), \b (word boundary). Using anchors eliminates unnecessary scanning across multi-megabyte buffers.
  • Lookarounds (Zero-Width Assertions): (?=...) (Positive Lookahead), (?!...) (Negative Lookahead), (?<=...) (Positive Lookbehind). Lookarounds validate conditions without consuming characters from the match stream.

Production Failure Modes: The Regular Expression Denial of Service (ReDoS)

The most catastrophic failure mode in regex implementations is Catastrophic Backtracking (ReDoS). Traditional Nondeterministic Finite Automata (NFA) regex engines (used in Node.js V8, Python re, Ruby, and Java) evaluate nested quantifiers using recursive backtracks.

1. The \(O(2^n)\) Algorithmic Time Bomb

Consider the seemingly harmless pattern designed to match comma-separated values: ^(a+)+$. When evaluated against a matching string (aaaa), it completes in 0.1ms. However, when evaluated against a non-matching string ending with an exclamation mark (aaaaaaaaaaaaaaaaaaaa!):

  • For 20 characters: 1,048,576 backtracks.
  • For 30 characters: 1,073,741,824 backtracks (freezes CPU core for 15 minutes!).
  • For 40 characters: Over 1,000 years of CPU time!

An attacker submitting a 40-character malformed string will freeze a Node.js single-threaded event loop permanently, crashing the web service for all users.

Production-Hardened ReDoS Protection via Regex Timeout (Node.js)

// Modern Node.js v20+ safe regex execution with timeout guards
const vm = require('vm');

function safeRegexExec(pattern, text, timeoutMs = 250) {
  const script = new vm.Script(`new RegExp(${JSON.stringify(pattern)}).test(${JSON.stringify(text)})`);
  const context = vm.createContext({});
  try {
    return script.runInContext(context, { timeout: timeoutMs });
  } catch (err) {
    if (err.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT') {
      throw new Error(`SECURITY WARNING: ReDoS Timeout Exceeded (${timeoutMs}ms)`);
    }
    throw err;
  }
}

DFA vs NFA Regex Engines: Why Google RE2 Eliminates ReDoS

Engine Architecture Underlying Algorithm Worst-Case Time Complexity Supports Backreferences? Vulnerable to ReDoS?
PCRE2 / V8 / Python re NFA (Backtracking) \(O(2^n)\) Exponential Yes (\1, \2) YES (High Risk)
Google RE2 / Rust regex DFA (Thompson NFA) \(O(n)\) Strictly Linear! No (Purposely omitted) NO (Immune to ReDoS)

Frequently Asked Questions (RegEx FAQ)

What is the difference between greedy and lazy matching?

Greedy quantifiers (*, +) match as many characters as possible before backtracking. Lazy / non-greedy quantifiers (*?, +?) match as few characters as possible, yielding immediately to the subsequent token. For parsing HTML or quotes, lazy matching prevents over-matching across tags.

What does the ‘s’ (dotAll) flag do in modern JavaScript?

By default, the dot (.) character matches any character except line breaks (\n, \r). Enabling the s flag instructs the dot to match all characters including newlines, making multiline block parsing straightforward.

Can regular expressions reliably parse HTML?

No. Regular expressions are theoretically designed for regular languages (Chomsky Type 3), whereas HTML has arbitrarily nested tags (Chomsky Type 2 Context-Free Language). Always use a dedicated DOM parser (such as BeautifulSoup, Cheerio, or DOMParser) for production HTML processing.

Advanced Regular Expression Grammar: Lookaround Mastery

Lookarounds (zero-width assertions) allow engineers to match characters based on what precedes or follows them without including those characters in the matched string result. They are critical for password validation, data masking, and string sanitation.

Lookaround Type Regex Syntax Description & Behavior Production Example
Positive Lookahead (?=pattern) Matches if pattern immediately follows the current position. \d+(?=px) matches “100” in “100px”
Negative Lookahead (?!pattern) Matches if pattern does NOT follow the current position. \d+(?!px) matches “100” in “100em” but not “100px”
Positive Lookbehind (?<=pattern) Matches if pattern immediately precedes the current position. (?<=\$)\d+ matches “50” in “$50”
Negative Lookbehind (?<!pattern) Matches if pattern does NOT precede the current position. (?<!\\)\$ matches unescaped dollar signs

The Strict Enterprise Password Validation Pattern

Lookaheads allow multiple independent validation rules to evaluate a single string simultaneously without enforcing strict ordering:

Production High-Entropy Password Regex

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$

Breakdown:
- ^ : Assert start of string
- (?=.*[a-z]) : Must contain at least one lowercase letter
- (?=.*[A-Z]) : Must contain at least one uppercase letter
- (?=.*\d) : Must contain at least one digit (0-9)
- (?=.*[@$!%*?&]) : Must contain at least one special character
- [A-Za-z\d@$!%*?&]{12,} : Minimum 12 characters in length
- $ : Assert end of string

Real-World ReDoS Post-Mortem: The Cloudflare Global Outage

In July 2019, Cloudflare deployed an updated Web Application Firewall (WAF) rule containing the expression (?:(?:\"|'|\]|\}|\\d|(?:nan|infinity|true|false|null|undefined|symbol|math)|\`|\-|\+)+[)]*\s*(?:\s*[\/\*]\s*|\s*\+-\+\s*|[\%&\|\^\<\>\*\/>]+\s*|\s*(?:&\lt;\|\>)\s*))+. When evaluated against certain HTTP headers, CPU utilization across Cloudflare’s global edge network surged to 100%, taking down major portions of the public internet for 27 minutes.

The Core Vulnerability: Grouping overlapping repetition operators (e.g., (a+)+ or ([a-zA-Z]+)*) creates branching state explosions. For non-matching inputs, the NFA engine explores every permutation before failing.

10 Essential Production-Hardened RegEx Patterns (2026 Cheatsheet)

  • Credit Card (Luhn Pre-Filter): ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})$
  • UUID v4 / v7: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$
  • Hex Color Code: ^#(?:[0-9a-fA-F]{3}){1,2}$
  • SemVer (Semantic Version): ^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?(?:\+[\da-zA-Z-]+)?$
  • Slug Generator Sanitizer: ^[a-z0-9]+(?:-[a-z0-9]+)*$
  • JWT Token Matcher: ^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$

Advanced Regular Expression Grammar: Lookaround Mastery

Lookarounds (zero-width assertions) allow engineers to match characters based on what precedes or follows them without including those characters in the matched string result. They are critical for password validation, data masking, and string sanitation.

Lookaround Type Regex Syntax Description & Behavior Production Example
Positive Lookahead (?=pattern) Matches if pattern immediately follows the current position. \d+(?=px) matches “100” in “100px”
Negative Lookahead (?!pattern) Matches if pattern does NOT follow the current position. \d+(?!px) matches “100” in “100em” but not “100px”
Positive Lookbehind (?<=pattern) Matches if pattern immediately precedes the current position. (?<=\$)\d+ matches “50” in “$50”
Negative Lookbehind (?<!pattern) Matches if pattern does NOT precede the current position. (?<!\\)\$ matches unescaped dollar signs

The Strict Enterprise Password Validation Pattern

Lookaheads allow multiple independent validation rules to evaluate a single string simultaneously without enforcing strict ordering:

Production High-Entropy Password Regex

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$

Breakdown:
- ^ : Assert start of string
- (?=.*[a-z]) : Must contain at least one lowercase letter
- (?=.*[A-Z]) : Must contain at least one uppercase letter
- (?=.*\d) : Must contain at least one digit (0-9)
- (?=.*[@$!%*?&]) : Must contain at least one special character
- [A-Za-z\d@$!%*?&]{12,} : Minimum 12 characters in length
- $ : Assert end of string

Real-World ReDoS Post-Mortem: The Cloudflare Global Outage

In July 2019, Cloudflare deployed an updated Web Application Firewall (WAF) rule containing the expression (?:(?:\"|'|\]|\}|\\d|(?:nan|infinity|true|false|null|undefined|symbol|math)|\`|\-|\+)+[)]*\s*(?:\s*[\/\*]\s*|\s*\+-\+\s*|[\%&\|\^\<\>\*\/>]+\s*|\s*(?:&\lt;\|\>)\s*))+. When evaluated against certain HTTP headers, CPU utilization across Cloudflare’s global edge network surged to 100%, taking down major portions of the public internet for 27 minutes.

The Core Vulnerability: Grouping overlapping repetition operators (e.g., (a+)+ or ([a-zA-Z]+)*) creates branching state explosions. For non-matching inputs, the NFA engine explores every permutation before failing.

10 Essential Production-Hardened RegEx Patterns (2026 Cheatsheet)

  • Credit Card (Luhn Pre-Filter): ^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})$
  • UUID v4 / v7: ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$
  • Hex Color Code: ^#(?:[0-9a-fA-F]{3}){1,2}$
  • SemVer (Semantic Version): ^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?(?:\+[\da-zA-Z-]+)?$
  • Slug Generator Sanitizer: ^[a-z0-9]+(?:-[a-z0-9]+)*$
  • JWT Token Matcher: ^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$

Regular Expression Security: Mitigating ReDoS (Catastrophic Backtracking)

Regular Expression Denial of Service (ReDoS) is an algorithmic complexity vulnerability where an attacker supplies a carefully crafted input string that forces a backtracking regex engine into exponential computation time \(O(2^n)\), freezing web application event loops and maxing CPU utilization at 100%.

Regex Engine Family Underlying Automaton Worst-Case Time Complexity Vulnerable to ReDoS? Primary Implementations
Backtracking NFA (PCRE, JS, Python) Non-deterministic Finite Automaton Exponential \(O(2^n)\) High Risk Node.js V8, Python re, PHP PCRE2, Ruby, Java
Linear DFA (RE2, Rust regex) Deterministic Finite Automaton Guaranteed Linear \(O(n)\) Zero ReDoS Risk Google RE2, Rust regex crate, Go regexp
Hybrid Just-In-Time (Hyperscan) Vectorized DFA/NFA SIMD Guaranteed Streaming Linear Zero ReDoS Risk Intel Hyperscan, Snort IDS, Suricata, Cloudflare WAF

Anatomy of a Vulnerable Regex: Evil Regex Patterns

A pattern is susceptible to catastrophic backtracking when it contains nested quantifiers with overlapping sub-patterns. Consider the canonical evil regex:

Catastrophic Backtracking Example

Pattern: ^(a+)+$
Input:   aaaaaaaaaaaaaaaaaaaaaaaaaaaa! (28 'a's followed by an exclamation mark)

Because the engine matches each a against both the inner and outer + loops, every non-matching character forces the engine to test \(2^{28}\) (268,435,456) combinatorial permutations before failing. In a single-threaded Node.js runtime, this locks the event loop for several minutes, dropping all concurrent user HTTP connections.

Production Hardening: 4 Rules to Prevent ReDoS

  • Enforce Regex Execution Timeouts: In environments like .NET or Python, specify an explicit match timeout (e.g., Regex.Match(input, pattern, TimeSpan.FromMilliseconds(200))).
  • Atomic Grouping & Possessive Quantifiers: Use possessive quantifiers (a++) or atomic groups (?>a+) to prevent the engine from saving backtracking checkpoints.
  • Adopt Linear Engines for User-Supplied Patterns: When building multi-tenant SaaS platforms where end-users define search filters, compile expressions using Google RE2 or Rust regex.
  • Use Safe Character Classes: Replace loose wildcards like .* with restrictive negated sets such as [^"<>\s]*.

Cross-Language Regex Quirks: JavaScript vs Python vs Go vs PHP

Although regular expression syntax looks universal, engine dialect differences frequently cause silent parsing bugs across microservices:

  • Lookbehind Assertions: Modern JavaScript (ES2018+) supports variable-length lookbehinds, whereas Python’s standard re module strictly requires fixed-length lookbehinds (e.g., (?<=abc) is valid, but (?<=a+) throws an error).
  • Named Capture Groups: JavaScript and Python use (?<name>...) and (?P<name>...) respectively. Go’s regexp strictly adheres to RE2 syntax, completely omitting backreferences and lookaround assertions to maintain strict \(O(n)\) performance guarantees.