Regex Tester & Debugger: Live Regular Expression Testing
Test, debug, and optimize regular expressions online in real time. Features live syntax highlighting, match extraction, capture group breakdown, complete token cheat sheets, and common validation patterns.
How to Use the Regex Tester
- 1Enter your regular expression pattern in the 'Regex' field without surrounding delimiters or forward slashes.
- 2Select your desired execution flags: Global ('g') for all matches, Case-Insensitive ('i'), Multiline ('m'), DotAll ('s'), or Unicode ('u').
- 3Paste or type your sample text into the 'Test String' editor.
- 4Review highlighted matches in the visual preview area. Hover over matches to inspect exact start and end string offsets.
- 5Inspect the 'Match Details' table below to verify captured subgroups, index positions, and check execution performance.
- 6Consult the Reference Tables below to find syntax tokens, character classes, anchors, lookarounds, and common recipes.
- •100% private client-side execution — your test data never leaves your browser.
- •Instant real-time match evaluation with zero latency.
- •Includes built-in safeguards against runaway backtracking on complex nested patterns.
About the Regex Tester & Debugger
The Regex Tester & Debugger is a high-performance, browser-based regular expression development workbench built for software developers, DevOps engineers, data analysts, and QA specialists. It evaluates complex regular expressions instantly against multi-line test strings using the standard ECMAScript (JavaScript) regex engine.
As you construct your pattern, the tool visually isolates every match, provides character index offsets, details captured parenthetical groups (including named capture groups), and executes full flag modifications (g, i, m, s, u, y). Whether you are crafting input sanitation filters, parsing server logs, extracting URLs, or debugging catastrophic backtracking risks, this tool delivers immediate clarity without sending sensitive payload data to external servers.
Our environment comes equipped with an exhaustive quick-reference syntax matrix, battle-tested validation recipes (email, phone, IPv4/IPv6, semantic versioning, passwords), and deep architectural guides on non-deterministic finite automata (NFA) behavior.
How the Regex Testing Engine Works
A regular expression (regex) is a declarative formal grammar pattern used to match, search, extract, and replace character sequences in strings. The testing engine compiles the pattern into a state machine that systematically scans the target text:
- Compilation & Flag Parsing: The regex string and chosen flags are compiled into an executable RegExp object. Modern engines optimize the pattern into bytecode for fast sequential matching.
- State Machine Traversal (NFA Execution): The engine advances through the test string character by character. When encountering alternatives (
|) or quantifiers (*,+), it attempts the longest path (greedy) and backtracks if subsequent token assertions fail. - Group Capture & Index Logging: For every successful match, the engine extracts the full matched substring, starting and ending index offsets, and populates numbered capture groups (
$1,$2) or named groups ((?<name>...)).
// Standard ECMAScript RegExp instantiation
const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const testString = "user@example.com";
const isValid = pattern.test(testString); // Returns true
// Match extraction with capture groups
const datePattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;
const match = datePattern.exec("Event date: 2025-11-20");
console.log(match.groups.year); // "2025"Worked Regular Expression Examples
All examples execute under standard ECMAScript regular expression specifications.
Complete Regular Expression Reference Sheets
Character Classes & Shorthand Escapes
| Token | Definition | Example Match | Negated Token & Definition |
|---|---|---|---|
| \d | Any digit [0-9] | '5' in 'Order 5' | \D: Any non-digit character |
| \w | Any word character [a-zA-Z0-9_] | 'x_1' in 'x_1 = 10' | \W: Any non-word character (spaces, symbols) |
| \s | Any whitespace [ \t\r\n\f] | ' ' or '\n' | \S: Any non-whitespace character |
| . | Any character except newline (unless 's' flag) | 'a', '9', '#' | [^\n]: Explicit non-newline class |
| [abc] | Character set (matches a, b, or c) | 'b' in 'bat' | [^abc]: Negated set (matches any char except a, b, c) |
| [a-z] | Character range (lowercase a to z) | 'm' in 'matrix' | [^a-z]: Any character outside range |
| \b | Word boundary assertion | Start or end of word | \B: Non-word boundary assertion |
Universal shorthand character classes supported across JavaScript, PCRE, Python, and Java.
Quantifiers: Greedy, Lazy, and Bound Limits
| Quantifier | Type | Repetition Rule | Example Behavior |
|---|---|---|---|
| * | Greedy | 0 or more times | a* matches '', 'a', 'aaaa' |
| *? | Lazy | 0 or more times (shortest match) | a*? matches shortest possible string |
| + | Greedy | 1 or more times | a+ requires at least one 'a' |
| +? | Lazy | 1 or more times (shortest match) | a+? matches exactly one 'a' if sufficient |
| ? | Greedy | 0 or 1 time (optional) | colou?r matches 'color' and 'colour' |
| ?? | Lazy | 0 or 1 time (prefers 0) | Prefers skipping optional token if valid |
| {n} | Exact | Exactly n repetitions | \d{4} matches exactly 4 digits (e.g., 2025) |
| {n,} | Minimum | At least n repetitions | \d{2,} matches 2 or more digits |
| {n,m} | Range | Between n and m repetitions | [a-z]{3,8} matches words 3 to 8 chars long |
Adding '?' after any greedy quantifier transforms it into a lazy (non-greedy) quantifier.
Anchors, Grouping, and Lookaround Assertions
| Syntax | Name | Mechanism | Sample Pattern |
|---|---|---|---|
| ^ | Caret (Start of String/Line) | Asserts position at start of input | ^https: |
| $ | Dollar (End of String/Line) | Asserts position at end of input | \.html$ |
| (abc) | Capturing Group | Groups tokens & captures matched text | (foo|bar) |
| (?:abc) | Non-Capturing Group | Groups tokens without memory allocation | (?:https?|ftp) |
| (?<id>abc) | Named Capturing Group | Captures text accessible by name | (?<area>\d{3}) |
| (?=abc) | Positive Lookahead | Asserts that pattern follows without consuming | \d+(?=px) |
| (?!abc) | Negative Lookahead | Asserts that pattern does NOT follow | foo(?!bar) |
| (?<=abc) | Positive Lookbehind | Asserts that pattern precedes without consuming | (?<=\$)\d+ |
| (?<!abc) | Negative Lookbehind | Asserts that pattern does NOT precede | (?<!\$)\d+ |
Lookarounds are zero-width assertions: they evaluate conditions without moving the string matching cursor.
Regular Expression Compilation Flags
| Flag | Name | Standard Functionality |
|---|---|---|
| g | Global Search | Finds all matches across the entire string rather than stopping after the first occurrence. |
| i | Case Insensitive | Treats uppercase and lowercase characters as identical (e.g., /cat/i matches 'CAT', 'Cat', 'cat'). |
| m | Multiline Mode | Causes ^ and $ to match the start and end of every line (delimited by \n), not just string boundaries. |
| s | DotAll (Single-line) | Enables the dot (.) special character to match newline characters (\n and \r). |
| u | Unicode Support | Enables full UTF-16 surrogate pair handling for emoji and non-Latin international character sets. |
| y | Sticky Mode | Matches only from the exact position indicated by the lastIndex property in the target string. |
ECMAScript standard flags supported in modern JavaScript environments.
10 Ready-to-Use Battle-Tested Regex Recipes
| Target Validation | Pattern (Regex) | Description / Notes |
|---|---|---|
| RFC 5322 Email | ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ | Standard web application email format validation |
| HTTP/HTTPS URL | ^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$ | Validates complete web protocol and domain routes |
| North American Phone | ^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$ | Matches (555) 000-0000, 555-000-0000, or 5550000000 |
| IPv4 Address | ^(?:(?: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]?)$ | Validates 4 octets from 0.0.0.0 to 255.255.255.255 |
| ISO 8601 Date | ^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$ | Validates YYYY-MM-DD formatted calendar dates |
| Hexadecimal Color | ^#(?:[0-9a-fA-F]{3}){1,2}$ | Validates 3-digit (#FFF) and 6-digit (#FFFFFF) CSS colors |
| Strong Password | ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$ | Minimum 8 chars with upper, lower, digit, and symbol |
| UUID v4 Identifier | ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$ | Standard 36-character canonical GUID/UUID v4 |
| HTML Tag Extractor | <([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>) | Matches opening, attributes, content, and closing tags |
| URL Slug Format | ^[a-z0-9]+(?:-[a-z0-9]+)*$ | Validates clean SEO permalinks (lowercase-with-hyphens) |
Production-grade patterns optimized for minimal backtracking overhead.
How the Regex Engine Evaluates Patterns: NFA vs. DFA and Backtracking
Understanding how a regular expression engine processes text is essential for writing efficient patterns. Modern programming languages generally utilize one of two architectural models:
- NFA (Non-Deterministic Finite Automaton): Engines used in JavaScript, Python, PCRE, Java, and .NET. NFA engines are regex-directed: they evaluate each token in the pattern sequentially and test characters in the string. If a path fails, the engine backtracks to the previous choice point and tries alternative branches. NFAs support advanced features like backreferences, lookarounds, and capture groups.
- DFA (Deterministic Finite Automaton): Engines used in tools like
awk,grep, and Google's RE2 library. DFA engines are text-directed: they scan the string in linear timeO(n)by keeping track of all possible matching states simultaneously. DFAs never backtrack, making them immune to catastrophic slowdowns, but they cannot support lookaround assertions or backreferences.
Greedy vs. Lazy vs. Possessive Quantifiers: Preventing Catastrophic Backtracking (ReDoS)
A common vulnerability in web development is Regular Expression Denial of Service (ReDoS). This occurs when an NFA engine attempts to evaluate an ambiguous pattern with nested repetitions on an invalid string, causing the number of backtracking steps to explode exponentially.
Consider the pattern (a+)+$ tested against aaaaaaaaaaaaaaaaaaaaaaaaaaaa!. The outer plus and inner plus can divide the string into billions of permutations. When the trailing exclamation mark fails to match, the engine tries every permutation, freezing the CPU thread.
To prevent catastrophic backtracking:
- Avoid Nested Quantifiers: Never nest repetitions like
(x+)*or(.*a)*. - Use Mutually Exclusive Character Classes: Instead of
<.*>, use<[^>]*>so the engine cannot match past the closing bracket. - Prefer Lazy Quantifiers for Delimiters: Use
.*?when extracting content between quotes or brackets. - Set Execution Timeouts: In production server environments, always enforce regex match timeouts (typically 200–500ms) on untrusted user inputs.
The Anatomy of Lookaround Assertions: Lookahead & Lookbehind Explained
Lookarounds are powerful zero-width assertions. They inspect what appears immediately before or after the current position in the string without consuming characters or including them in the matched result:
- Positive Lookahead
(?=...): Asserts that the enclosed sub-pattern matches immediately following the current position. For example,\d+(?=px)matches100in100px, but does not match100em. The letters 'px' are verified but excluded from the match. - Negative Lookahead
(?!...): Asserts that the enclosed sub-pattern does NOT follow. For example,foo(?!bar)matches 'foo' in 'foobaz' and 'food', but rejects 'foobar'. - Positive Lookbehind
(?<=...): Asserts that the enclosed sub-pattern precedes the current position. For example,(?<=\$)\d+matches50in$50, leaving the dollar sign unselected. - Negative Lookbehind
(?<!...): Asserts that the enclosed sub-pattern does NOT precede. For example,(?<!\$)\d+matches numbers not prefixed with currency markers.
Regex Dialect Comparison: JavaScript (ECMAScript) vs. PCRE vs. Python
While regular expression basics are universal, specific features vary between programming languages:
- JavaScript (ECMAScript): Supported natively in this tester. Features Unicode property escapes (
\p{Letter}), lookbehind assertions (ES2018+), named capture groups ((?<name>)), and the DotAllsflag. It does not support possessive quantifiers (++) or atomic groups ((?>...)). - PCRE (PHP, Apache, NGINX): Highly feature-rich. Supports atomic grouping, possessive quantifiers, subroutine recursion (
(?R)for nested parentheses parsing), and conditional matching(?(condition)true|false). - Python (
remodule): Supports named groups with syntax(?P<name>...)and backreferences(?P=name). Python's standardreengine requires fixed-width lookbehinds, whereas the third-partyregexmodule allows variable-length lookbehinds. - Go (
regexppackage): Uses Google's RE2 engine. Guarantees linear-time matching without backtracking, but intentionally omits backreferences and lookaround assertions.
Capturing Groups vs. Non-Capturing Groups vs. Named Groups
Parentheses serve two distinct purposes in regex: logical grouping of tokens and memory storage of matched text:
- Standard Capturing Group
(...): Saves the matched characters in numerical registers ($1,$2, etc.). Useful when extracting parts of a string or using regex replacement. However, capturing consumes memory and slight processing overhead. - Non-Capturing Group
(?:...): Groups tokens for quantifier application (e.g.,(?:https?|ftp):\/\/) without creating a capture memory buffer. Always use non-capturing groups when you only need logical grouping without extraction. - Named Capturing Group
(?<name>...): Associates a human-readable identifier with the group. Instead of remembering whether the zip code was group 3 or group 4, you accessmatch.groups.zipCodedirectly in code, improving code clarity and maintainability.
Best Practices for Writing High-Performance, Maintainable Regular Expressions
To keep regex logic clean, robust, and performant in production software systems, follow these five engineering guidelines:
- Anchor Your Expressions: Whenever validating full inputs (e.g., form fields), always include
^and$. Without anchors,\d{5}will match '12345' inside 'abc12345xyz'. - Favor Concrete Character Classes Over Dot: Avoid over-relying on wildcard
.*. Replace it with explicit exclusion sets like[^\s"<>]+to prevent unintended greedy consumption. - Compile Regex Objects Once: In loops or high-throughput request handlers, compile your regex once at the module scope rather than creating new
RegExpinstances per call. - Add Comments in Complex Patterns: In languages that support the verbose/extended
xflag (or by commenting in code), document each logical section of complex regex strings. - Do Not Use Regex for HTML/XML Parsing: Context-free grammars with arbitrary nesting (such as HTML tags) cannot be parsed reliably by regular expressions. Always use dedicated DOM parsers (like BeautifulSoup, Cheerio, or DOMParser) for structured markup.
Who Uses the Regex Tester and Why
- ✓Full-Stack & Backend Developers: Test form validation patterns, sanitize user input, and structure API payload verification.
- ✓DevOps & Site Reliability Engineers (SREs): Write and test log-parsing filters for CloudWatch, Datadog, Splunk, Graylog, and Fluentd.
- ✓Data Engineers & Scientists: Clean unstructured text datasets, tokenize NLP corpora, and extract numerical metrics from raw text.
- ✓QA & Automation Engineers: Validate string outputs, assert API response formats, and verify database schema constraints.
- ✓Cybersecurity Analysts: Develop SIEM detection rules, identify payload injection patterns, and configure Snort/Suricata network signatures.
Limitations & Practical Tips
Known Limitations
- •This tester runs the ECMAScript (JavaScript) regular expression engine. Advanced features exclusive to PCRE (such as recursive pattern matching (?R), atomic groups (?>...), or branch resets) are not supported by the browser engine.
- •JavaScript RegExp historically required fixed-length patterns in lookbehinds, though modern browsers support variable-length lookbehinds.
- •Extremely deep recursive patterns may trigger browser execution limits to protect system responsiveness.
Tips for Best Results
- →Always test with both matching inputs and negative edge cases (e.g. empty strings, extra spaces, special symbols) to verify pattern boundaries.
- →If searching multiline logs, remember to enable both the Multiline ('m') and Global ('g') flags.
- →When validating emails, remember that the RFC 5322 specification permits complex edge cases. For production account registration, verify via email delivery confirmation rather than an overly strict regex.
Frequently Asked Questions About Regular Expressions
- What is a regular expression (regex)?
A regular expression is a formalized pattern string used by search algorithms to find, extract, validate, and manipulate text. Regex is natively supported across virtually every modern programming language, text editor, command-line utility (grep, sed, awk), and database engine.
- What is the difference between greedy and lazy matching?
A greedy quantifier (like
*or+) matches as much text as possible while still allowing the overall pattern to succeed. A lazy quantifier (like*?or+?) matches as little text as possible. For example, when searching<b>bold</b>, the greedy pattern<.*>matches the entire string, while lazy<.*?>matches just the first tag<b>.- What are zero-width lookaround assertions?
Lookarounds (lookaheads
(?=...)/(?!...)and lookbehinds(?<=...)/(?<!...)) check whether specific characters precede or follow the current position without including those characters in the matched string result. They are called 'zero-width' because they do not consume characters in the text matching buffer.- What do the regex flags g, i, m, s, u mean?
g (global): Finds all matching instances instead of stopping after the first match. i (case-insensitive): Ignores capital vs. lowercase distinctions. m (multiline): Enables
^and$to match the start and end of every line. s (dotAll): Allows the dot (.) token to match newlines. u (unicode): Enables full UTF-16 code point matching for emoji and foreign scripts.- How do I escape special characters in regex?
In regex, the characters
. * + ? ^ $ { } [ ] ( ) | \carry syntactic meaning. To match them literally, prefix them with a backslash:\.matches a literal dot,\$matches a dollar sign, and\\matches a literal backslash.- What is Catastrophic Backtracking and ReDoS?
Catastrophic backtracking occurs when an NFA regex engine attempts to match nested repetitions (like
(a+)+$) against non-matching text. The engine tests an exponential number of permutations, spiking CPU utilization to 100% and causing application freezes (Regular Expression Denial of Service). It is mitigated by removing nested quantifiers and using atomic or mutually exclusive sets.- Why shouldn't I parse HTML with regular expressions?
HTML is a context-free grammar with potentially infinite nesting, arbitrary whitespace, comments, script tags, and unclosed elements. Regular expressions can only recognize regular languages. Attempting to parse complex HTML with regex inevitably leads to fragile code and parsing failures. Use a dedicated HTML DOM parser instead.
- What is the difference between \d and [0-9]?
In pure ASCII engines,
\dand[0-9]are identical. However, in engines with full Unicode flag enabled (/u) in some languages (like Python or .NET),\dmay match all Unicode decimal digit characters (such as Arabic or Devanagari numerals), whereas[0-9]strictly matches ASCII digits 0 through 9.- What is the difference between a capturing group and a non-capturing group?
A capturing group
(abc)stores the matched text in memory so it can be referenced later in replacement patterns or extracted by array index. A non-capturing group(?:abc)applies quantifiers or alternates without allocating memory for storage, making execution faster.- Can I validate an entire email address reliably using regex?
A standard regex like
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$catches 99.9% of user typos in web registration forms. However, the official RFC 5322 standard allows IP addresses, comments, and quoted strings inside email handles, requiring a 6,000-character regex. Best practice is to use a sensible basic regex on the frontend, and confirm validity by sending a confirmation link.
Looking for more tools like this? Browse all Developer Tools →
More Developer Tools
JSON Formatter
Format, validate, and minify JSON online. Instantly beautify or compress JSON data with syntax highlighting. Free JSON formatter and validator.
Base64 Encoder / Decoder
Encode text to Base64 or decode Base64 strings back to plain text online. Free Base64 encoder decoder tool for developers and data analysts.
URL Encoder / Decoder
Encode or decode URLs and query strings online. Convert special characters to percent-encoding instantly. Free URL encoder decoder for developers.
Password Generator
Generate strong, random passwords instantly. Customize length and character types. Free secure password generator tool for safe online accounts.
Color Converter
Convert colors between HEX, RGB, HSL, and HSB online free. Pick colors visually and copy CSS values in any format instantly — no signup needed.
Unix Timestamp Converter
Convert Unix timestamps to human-readable dates and times online free. Convert dates to Unix timestamps in seconds or milliseconds instantly.
You Might Also Like
Word Counter
Count words, characters, sentences, and paragraphs instantly. Free online word counter tool with reading time estimate for writers and students.
Character Counter
Count characters with and without spaces instantly. Free online character counter for Twitter, Instagram, SMS, and meta tag length limits.
Percentage Calculator
Calculate percentages, percentage change, and what percent one number is of another. Free online percentage calculator for everyday math.
Regex Tester & Debugger — Free Client-Side Developer Tool by CalcDash.