A Regex Debugger compiles ECMAScript regular expressions in browser memory, computes non-overlapping capture offsets and numbered/named capture groups (`$1`, `$2`), warns on nested quantifiers prone to Catastrophic Backtracking (ReDoS, exponential O(2^n) runtime in NFA engines), and exports safe copy-ready JavaScript/TypeScript and Python `re.finditer` boilerplate.
How to Use Regex Pattern Tester
- 1Enter Your Pattern & Flags or Select a Common Preset
Pick Markdown Links, Semantic Version, or IPv4 Addresses, or type a custom regular expression alongside ECMAScript flags (`g`, `i`, `m`, `s`, `u`).
- 2Verify Live Highlights, Offset Indexes & Capture Groups
Watch exact highlighted substrings update across your test corpus while inspecting numbered capture groups (`$1`, `$2`) and any ReDoS backtracking warnings.
- 3Simulate Substitutions and Export JS / Python Code
Test `.replace()` transformation rules live and click Copy JS / Python Snippet to move the verified expression straight into production.
Core Capabilities & Specifications
- Real-time inline match highlighting across multi-line text with character offsets
- Displays full match string and numbered capture groups (`$1`, `$2`, ...)
- Interactive substitution preview supporting `$1`, `$2`, and `$&` replacement tokens
- Automated nested-quantifier ReDoS backtracking hazard detection
- One-click JavaScript / TypeScript & Python `re` boilerplate export
Avoiding Catastrophic Backtracking (ReDoS) in Production APIs
JavaScript's ECMAScript `RegExp` engine, Python's `re`, Java `Pattern`, and PCRE implement backtracking Non-deterministic Finite Automata (NFA). Whenever a group contains an inner repetition inside an outer quantifier—such as `(a+)+$`, `([a-zA-Z0-9._-]+)*@`, or `(.*?,){12}fail`—an attacker sending a long non-matching suffix triggers exponential O(2^n) backtracking permutations, pinning a single Node.js event-loop thread at 100% CPU for minutes.
By contrast, Rust's `regex` crate and Go's standard `regexp` (based on Google RE2) execute Thompson NFA / lazy DFA finite automata guaranteeing strict linear O(n) evaluation regardless of input—intentionally omitting backreferences and arbitrary lookaround to protect production uptime.
export function safeMatchAll(input: string, pattern: RegExp, maxInputChars = 16384): RegExpMatchArray[] {
if (input.length > maxInputChars) {
throw new Error(`Input exceeds safe regex upper bound (${maxInputChars} chars)`);
}
const cloned = new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`);
return [...input.matchAll(cloned)];
}Why JavaScript `regex.test()` Fails Intermittently with the `g` Flag
One of the highest-frequency JavaScript production bugs happens when declaring a global `const SLUG_RE = /^[a-z0-9-]+$/g` at module scope and calling `SLUG_RE.test(slug)` inside repeated handler calls. Because global (`/g`) and sticky (`/y`) `RegExp` objects mutate `.lastIndex` internally after a match, the first call returns `true` and advances `.lastIndex` past the string—causing the second call on identical input to start mid-string or end-of-string and return `false`!
Use stateless patterns (omit `g` for `.test()` boolean validation) or prefer `.matchAll()` / fresh `new RegExp` instances when extracting iterative tokens.
Greedy vs Lazy Quantifiers and Non-Capturing Groups (`?:`)
Standard quantifiers `*`, `+`, and `{m,n}` are greedy: `.*` consumes until the very last occurrence on the line before backtracking. Adding `?` (`.*?`, `+?`) switches to lazy matching, stopping at the earliest delimiter—crucial when scraping Markdown links `[label](url)` or quoted tokens where two matches sit on the same line.
Meanwhile, grouping alternatives purely for precedence (`(?:https?|wss?)`) avoids allocating needless capture-group slots (`$1`, `$2`), improving clarity and parser performance.
# Python named group extraction
import re
LOG_RE = re.compile(r"(?P<level>ERROR|WARN)\s+req=(?P<req_id>[a-f0-9-]+)\s+ms=(?P<latency>\d+)")
for m in LOG_RE.finditer("ERROR req=8f2a9c ms=412"):
print(m.groupdict()) # {'level': 'ERROR', 'req_id': '8f2a9c', 'latency': '412'}Zero-Length Assertion Guard in Match Loops
Patterns capable of matching an empty string (like `a*` or `^` or lookaheads) leave `.lastIndex` unchanged inside naïve `while ((m = re.exec(s)))` loops—causing an infinite browser freeze! Production debuggers must explicitly increment `re.lastIndex++` whenever `m[0] === ""` to guarantee termination.
Engineering Comparison Matrix
| Engine / Runtime | Algorithm Family | Worst-Case Time | Lookbehind / Backrefs |
|---|---|---|---|
| JavaScript ES2024 `RegExp` | Backtracking NFA | Exponential (ReDoS on nested quantifiers) | Full variable lookbehind + backrefs |
| Python `re` | Backtracking NFA | Exponential on pathological inputs | Fixed-width lookbehind + backrefs |
| Rust `regex` Crate | Thompson NFA / Lazy DFA | Guaranteed O(n) linear | Intentionally omitted for O(n) safety |
| Go `regexp` / Google RE2 | Thompson NFA / DFA | Guaranteed O(n) linear | Intentionally omitted for O(n) safety |
Common Production Pitfalls to Avoid
- •Sharing a stateful `/g` `RegExp` constant across `.test()` validation calls causing alternating true/false bugs via `.lastIndex`.
- •Leaving unescaped literal dots `.` inside domain patterns (`example.com` matches `exampleXcom`).
- •Deploying unanchored nested quantifiers `(.*)+` on user-controlled HTTP headers, emails, or Markdown strings.
- •Writing `while ((m = re.exec(text)))` without advancing `re.lastIndex` on zero-length matches (`m[0] === ''`).
- •Forgetting the `/s` (dotAll) flag when matching across newline boundaries with `.+`.
Frequently Asked Questions
Why does `regex.test()` alternate true and false when the `g` flag is set?
In JavaScript, `RegExp` instances carrying the `g` or `y` flag store mutable search state in `.lastIndex`. After returning true on a match, `.lastIndex` points to the end of that match, so the subsequent `.test()` starts from there and fails.
What causes Catastrophic Backtracking (ReDoS)?
Nested quantifiers such as `(a+)+` or overlapping alternations like `(a|a?)+` create exponentially branching search paths when a backtracking NFA engine tries to prove a long near-matching string does NOT match.
What is the difference between `()` and `(?:)` in regular expressions?
`(...)` creates a numbered capturing group accessible via `$1`/`$2` and match arrays, whereas `(?:...)` groups subpatterns cleanly for repetition or alternation without allocating capture slots.
How do I match across multiple lines including newlines in JavaScript?
Enable the `s` (dotAll) flag so `.` matches newline characters (`\n`, `\r`), and combine with `m` (multiline) if you want `^` and `$` anchors to match individual line boundaries instead of just start/end of input.
Why do I need `\\` double backslashes inside string literals like `new RegExp()`?
Inside a JavaScript or Python quoted string, one backslash introduces a string escape sequence (`\d` -> `d`), so you either write double backslashes `"\\d+"`, a regex literal `/\d+/`, or raw strings `r"\d+"` in Python.
When should I replace a complex regex with a real parser?
Never parse recursive/nested grammars such as arbitrary HTML, nested JSON, or balanced parentheses using regular expressions. Reach for DOM parsers, `JSON.parse`, or lightweight recursive-descent lexers cleanly.

