Regex Tester

Test and debug regular expressions in real time. Highlights matches, shows capture groups, and includes a cheat sheet.

Developer ToolsFreeNo Signup
Regex Tester
Free Tool

How to use Regex Tester

**What Is a Regular Expression?** A regular expression (regex) is a sequence of characters that defines a search pattern. Developers use regex to validate input, parse text, search and replace strings, and extract data from logs or files. Regex is supported in nearly every programming language — JavaScript, Python, Java, Ruby, Go, PHP — and in command-line tools like grep, sed, and awk. Despite their intimidating syntax, regex patterns are constructed from a small set of building blocks that follow consistent rules across environments. Diztool's Regex Tester lets you write a pattern, paste test text, and see every match highlighted in real time — no setup, no imports, no console.log required. **Step-by-Step: How to Use the Regex Tester** **Step 1 — Enter your pattern.** Type your regex in the Pattern field. Do not include the surrounding slashes (/) that some languages use as delimiters — just the expression itself. For example, to match a US email address, enter: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ **Step 2 — Select your flags.** Flags modify how the engine interprets the pattern. The most common are listed below. Check the ones you need before running the match. **Step 3 — Paste your test string.** Enter the text you want to search in the Test String box. This can be a single line, a multiline block, a sample log file, or a list of values — whatever your real input looks like in production. **Step 4 — Read the results.** The tool highlights every match in the test string. Below the input you'll see the match count, each matched value, and the contents of any capture groups. If zero matches appear, the pattern did not match — check your flags, escape characters, and anchors. **Regex Quick Reference Cheat Sheet** Before diving into examples, bookmark this metacharacter reference. These symbols work across JavaScript, Python, PCRE, Java, and Ruby: | Symbol | Meaning | Example | |---|---|---| | . | Any character except newline | a.c matches "abc", "a1c" | | \d | Any digit [0-9] | \d{3} matches "123" | | \D | Any non-digit | \D+ matches "abc" | | \w | Word character [a-zA-Z0-9_] | \w+ matches "hello_world" | | \W | Non-word character | \W matches spaces, punctuation | | \s | Whitespace (space, tab, newline) | \s+ matches multiple spaces | | \S | Non-whitespace | \S+ matches a single token | | ^ | Start of string (or line with m flag) | ^Hello matches "Hello world" | | $ | End of string (or line with m flag) | world$ matches "Hello world" | | \b | Word boundary | \bcat\b matches "cat" not "cats" | | * | 0 or more | a* matches "", "a", "aaa" | | + | 1 or more | a+ matches "a", "aaa" but not "" | | ? | 0 or 1 (also makes quantifiers lazy) | colou?r matches "color", "colour" | | {n} | Exactly n | \d{4} matches "2024" | | {n,m} | Between n and m | \d{2,4} matches "12", "123", "1234" | | [abc] | Character class | [aeiou] matches any vowel | | [^abc] | Negated class | [^\d] matches any non-digit | | (abc) | Capture group | (\d+) captures the digits | | (?:abc) | Non-capturing group | (?:\d+) groups without capturing | | a\|b | Alternation | cat\|dog matches "cat" or "dog" | **Understanding Regex Flags** Flags are single letters appended to a regex literal that change how matching works. Here is a reference table for JavaScript regex flags, which closely mirror the flags available in Python (re module), Java, and PCRE: | Flag | Name | Effect | |---|---|---| | g | Global | Find all matches, not just the first | | i | Case-insensitive | Match uppercase and lowercase equally | | m | Multiline | ^ and $ match start/end of each line, not just the whole string | | s | Dotall | . matches newlines (\n) in addition to all other characters | | u | Unicode | Enables full Unicode matching and properties | | y | Sticky | Matches only from lastIndex position; used for stateful parsing } In Python's re module, the equivalent flags are re.IGNORECASE (i), re.MULTILINE (m), re.DOTALL (s), and re.UNICODE (u). PCRE, used in PHP and many server-side tools, supports the same set with near-identical semantics. **Real-World Regex Examples** These production-ready patterns demonstrate how regex solves common developer problems: **Email validation:** ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ Test: user@example.com ✓ | user+tag@sub.example.co.uk ✓ | notanemail ✗ **US phone number (multiple formats):** ^\+?1?\s*\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$ Matches: (555) 867-5309, 555.867.5309, 5558675309, +1 555-867-5309 **US ZIP code (5-digit and ZIP+4):** ^\d{5}(-\d{4})?$ Matches: 90210 and 90210-1234 **IPv4 address:** ^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$ Matches: 192.168.1.1, 10.0.0.1 | Rejects: 999.1.1.1 **Strong password (8+ chars, 1 uppercase, 1 digit, 1 special):** ^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*]).{8,}$ Matches: P@ssword1 ✓ | password ✗ | Password ✗ **URL (http/https):** https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/=]*) Matches: https://diztool.com/tools/regex-tester **Hex color code:** ^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$ Matches: #FF5733, #f53, #ffffff | Rejects: #GGG, #12345 **ISO 8601 date (YYYY-MM-DD):** ^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$ Matches: 2024-03-15, 2000-12-31 **Regex Substitution and Replace** A regex tester's second most-used mode — after matching — is substitution. Substitution finds every occurrence of a pattern and replaces it with new content. This is how you use regex in production for data transformation: **JavaScript String.prototype.replace():** const result = 'Hello World'.replace(/world/i, 'Regex'); // → 'Hello Regex' With the g flag for all occurrences: const cleaned = '2024-03-15'.replace(/-/g, '/'); // → '2024/03/15' **Python re.sub():** import re cleaned = re.sub(r'\s+', ' ', 'too many spaces') # → 'too many spaces' Back-references in substitution let you rearrange capture groups. In JavaScript: `'John Smith'.replace(/(\w+) (\w+)/, '$2, $1')` → `'Smith, John'`. In Python: `re.sub(r'(\w+) (\w+)', r'\2, \1', 'John Smith')` gives the same result. This technique is used constantly in data normalization — reformatting dates, swapping name order, transforming API response keys. **Named Capture Groups — Pro Tip** Most developers start with numbered capture groups: (\d{4})-(\d{2})-(\d{2}) captures year in group 1, month in group 2, day in group 3. Named groups are more readable and maintainable: (?<year>\d{4})-(?<month>0[1-9]|1[0-2])-(?<day>0[1-9]|[12]\d|3[01]) In JavaScript you access them as match.groups.year, match.groups.month, match.groups.day. In Python: match.group('year'). Named groups make long patterns self-documenting and eliminate off-by-one errors when a pattern gains or loses a capturing group. **Lookahead and Lookbehind** Lookahead (?=...) and lookbehind (?<=...) match a position without consuming characters. They let you write patterns that require context without including it in the result. Positive lookahead — match digits only when preceded by "$": (?<=\$)[0-9,]+(?:\.[0-9]{2})? matches 1,299.99 from "Total: $1,299.99" Negative lookahead — match "http" only when NOT followed by "s": http(?!s) matches http:// but not https:// **Regex Engine Differences by Language** Not all regex engines are equal. The patterns you test here are JavaScript-based, but here are key differences when porting to other languages: | Engine | Language | Lookaheads | Named Groups | POSIX Classes | |---|---|---|---|---| | V8 (ECMAScript) | JavaScript | ✓ | (?<name>...) | ✗ | | PCRE2 | PHP, grep -P | ✓ | (?<name>...) | ✓ | | java.util.regex | Java | ✓ | (?<name>...) | ✗ | | re module | Python | ✓ | (?P<name>...) | ✗ | | RE2 | Go, Rust | ✗ | (?P<name>...) | ✓ | | Regexp | Ruby | ✓ | (?<name>...) | ✓ | **Critical Go/RE2 difference:** Go uses the RE2 engine, which deliberately does not support lookaheads or lookbehinds. If you write a pattern with (?=...) here and then copy it to Go code, it will fail to compile. For Go, rewrite lookaheads as multi-step string operations or use the regexp/syntax package to validate before using. **POSIX Character Classes** (available in PCRE, Ruby, Go): [:alpha:] = letters, [:digit:] = digits, [:alnum:] = letters+digits, [:space:] = whitespace, [:upper:] = uppercase letters. In PCRE: [[:alpha:]] is equivalent to [a-zA-Z]. **Unit Testing Your Regex** One technique regex101 popularized is treating regex like code — with unit tests. Before deploying a validation regex to production, build a test matrix: | Test string | Should match? | Why | |---|---|---| | user@example.com | Yes | Standard email | | user+tag@sub.example.co.uk | Yes | Plus addressing + subdomain + multi-TLD | | user@.com | No | Missing domain name | | @example.com | No | Missing local part | | user @example.com | No | Space not allowed | | user@exam_ple.com | No | Underscore in domain invalid | For the US phone pattern, test all formatting variants you expect in your form data — (555) 867-5309, 555-867-5309, 5558675309, +15558675309 — and several that should fail: 55-867-5309, 123-456-789. A pattern that only passes the obvious test case will fail in production on the first unusual but valid input. **Common Regex Mistakes and How to Avoid Them** **Mistake 1: Catastrophic backtracking.** Patterns like (a+)+ can cause exponential matching time on strings that nearly match. If your regex hangs or times out on long strings, look for nested quantifiers on overlapping character classes. Rewrite (a+)+ as a+ and use atomic groups or possessive quantifiers when available. **Mistake 2: Forgetting to escape the dot.** In regex, . matches any character except a newline. If you want a literal dot — for example, in a domain or file extension — escape it as \.. The pattern .com matches "acom", "bcom"; the pattern \.com matches only ".com". **Mistake 3: Anchoring errors.** Without ^ and $, a pattern like \d{5} matches "12345" inside the longer string "abc123456xyz". Always anchor validation patterns with ^ at the start and $ at the end for full-string matches. **Mistake 4: Wrong flag for multiline input.** If your test string has line breaks and you want ^ and $ to match line boundaries, enable the m (multiline) flag. Without it, ^ only matches the very beginning and $ only the very end of the whole string. **Mistake 5: Using regex for HTML or JSON parsing.** Regex cannot reliably parse nested or recursive structures. Use DOMParser in JavaScript, BeautifulSoup in Python, or JSON.parse. Reserve regex for flat, predictable string patterns. **Practical Workflow: Debugging a Production Pattern** 1. Copy the failing regex from your code into the Pattern field. 2. Paste a sample of your actual production data — a log line, a form value, an API response snippet — into the Test String box. 3. Enable the g flag to see all matches. 4. If nothing matches, remove anchors (^ and $) first to see if the core pattern matches anywhere in the string. 5. Add anchors back and adjust until the match is exactly what your code expects. 6. Copy the validated pattern back into your codebase. This iterative approach — test with real data, not invented strings — catches edge cases that unit tests with simple examples miss. A pattern that correctly validates "user@example.com" might fail on "user+tag@sub.example.co.uk" without the right character class coverage. **Performance Tips for Complex Patterns** For patterns run against thousands of records (log processing, batch validation), performance matters. Compiled patterns in Python (re.compile(pattern)) are faster than re.match(pattern, string) called in a loop. In JavaScript, storing a RegExp object outside a loop avoids recompilation on each iteration. Character classes ([a-z]) are faster than alternations (a|b|c|...|z) for single-character matching. Possessive quantifiers (\d++) and atomic groups, available in PCRE and Java, prevent backtracking entirely — use them when the match is deterministic.

Frequently Asked Questions

Recommended

Related Tools