Regex Tester preview

Regex Tester

Write a regular expression and see every match highlighted in your test text as you type. The tool uses your browser's JavaScript RegExp engine, so results match JavaScript and TypeScript. Other languages can treat some patterns differently.

Key features

  • Real-time match highlighting as you type
  • List of the distinct matched strings under the highlighted text
  • Toggles for the g, i, m, and s flags
  • Error messages for invalid patterns

Guide

Regular expressions are a pattern matching language used in every major programming language, text editor, command-line tool, and database system. They let you search, match, extract, and replace text based on patterns rather than fixed strings. A regex tester gives you a sandbox to write and debug patterns with instant visual feedback on what matches and what does not.

This tool lets you type a regular expression and a test string, then see matches highlighted as you type. You get a match count, a list of the distinct matched strings, and toggles for four flags. It runs in your browser using JavaScript's RegExp engine.

How Regular Expressions Work

A regular expression defines a search pattern as a sequence of characters and metacharacters. The simplest regex is a literal string: the pattern hello matches the text "hello" exactly wherever it appears. The power comes from special characters (metacharacters) that represent classes, quantities, positions, and groups.

Character classes match categories of characters. A dot (.) matches any single character except a newline. \d matches any digit (0-9). \w matches any word character (letters, digits, underscore). \s matches any whitespace (space, tab, newline, carriage return). \D, \W, and \S are the negated versions (non-digit, non-word, non-whitespace). Custom character classes use square brackets: [aeiou] matches any vowel, [a-z] matches any lowercase letter, [^0-9] matches any non-digit character.

Quantifiers control how many times a pattern repeats. * means zero or more, + means one or more, ? means zero or one, {n} means exactly n times, {n,} means n or more, and {n,m} means between n and m times. For example, \d+ matches one or more consecutive digits, [a-z]{3,5} matches 3 to 5 lowercase letters, and colou?r matches both color and colour.

Anchors match positions rather than characters. ^ matches the start of a string (or line in multiline mode), and $ matches the end. \b matches a word boundary (the position between a word character and a non-word character). These are essential for ensuring your pattern matches at the right position and does not capture partial matches from longer strings.

Groups and captures use parentheses. (abc) creates a capturing group that matches "abc" and remembers the matched text. (?:abc) is a non-capturing group that matches but does not remember. (?<name>abc) is a named capturing group. Backreferences like \1 refer to the first captured group's value. Alternation uses the pipe character: cat|dog matches either "cat" or "dog".

Using the Regex Tester

Type your pattern in the regex input field and your test text below it. Matches are highlighted instantly as you type. The tool shows:

  • Every match in the test string, highlighted in yellow
  • A match count, or No matches when nothing matches
  • A list of the distinct matched strings under the highlighted text
  • Flag toggles for g (global), i (case-insensitive), m (multiline), and s (dotAll)
  • The browser error message when the pattern is invalid

Keep the global (g) flag on, which is the default, so the count includes every match. Add the i flag when case does not matter. Use the m flag when your test text has multiple lines and you want ^ and $ to match line starts and ends rather than the start and end of the whole text. Enable the s flag if you need dot (.) to match newline characters. The tool has no u toggle, so Unicode property escapes such as \p{L} do not work here. Patterns that can match an empty string, such as a* or ^ on its own, add one empty match per position to the count. The highlight shows only matches with at least one character.

The instant feedback loop is what makes a regex tester valuable. Instead of writing a pattern, running a script, checking the output, editing the pattern, and repeating, you see results in real-time as you modify the pattern or the test text.

Practical Patterns You Will Use Often

Email validation (simplified): [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} matches most email addresses. This is not RFC 5322 compliant (almost no regex is, because the RFC allows quoted strings, comments, and other rarely-used syntax), but it works for form validation where you want to catch obvious typos. For strict validation, send a confirmation email.

URL matching: https?:\/\/[^\s]+ matches HTTP and HTTPS URLs. For more precision, use https?:\/\/[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\/[^\s]*)? to require a valid domain name. For extracting URLs from text that might contain trailing punctuation, use https?:\/\/[^\s.,;:!?)\]]+.

IPv4 address: \b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b matches patterns that look like IP addresses. Note that this also matches invalid values like 999.999.999.999. For strict validation that only matches valid octets (0-255), use \b(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\b.

Date in YYYY-MM-DD format: \d{4}-\d{2}-\d{2} matches the pattern. To capture parts: (\d{4})-(\d{2})-(\d{2}) gives you year, month, and day in groups 1, 2, and 3. To match only valid months and days, add range checks: (\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]).

Hex color code: #([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b matches both 3-digit and 6-digit hex colors like #FFF and #3a7bd5.

Phone numbers (US): \(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4} matches formats like (555) 123-4567, 555-123-4567, and 5551234567.

HTML tag extraction: <(\w+)[^>]*>(.*?)<\/\1> matches paired opening and closing tags and captures the tag name (group 1) and content (group 2). This is fine for simple extraction but not for parsing arbitrary HTML. Nested tags, self-closing tags, and attributes with > characters can break this pattern. Use a DOM parser for complex HTML.

Log line parsing: (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \[(\w+)\] (.+) captures timestamp (group 1), log level (group 2), and message (group 3) from log lines like 2026-03-21 14:30:00 [ERROR] Connection refused.

CSV field extraction: (?:^|,)("(?:[^"]|"")*"|[^,]*) handles both quoted and unquoted CSV fields, including fields that contain commas within quotes.

Capture Groups and Extraction

Capture groups are one of the most powerful regex features. They let you extract specific parts of a match. In the regex (\w+)@(\w+)\.(\w+) applied to alice@example.com, group 0 is the full match alice@example.com, group 1 is alice, group 2 is example, and group 3 is com.

Named groups make patterns more readable and maintainable. Instead of (\d{4}), write (?<year>\d{4}). In JavaScript, the match object includes a .groups property: match.groups.year returns the year value. This is especially useful when your pattern has many capture groups and referring to them by number becomes confusing.

Non-capturing groups (?:...) are useful when you need grouping for alternation or quantification but do not need to capture the match. For example, (?:https?|ftp):\/\/ groups the protocol alternatives without creating a capture group. This keeps your group numbering clean and is slightly more efficient.

This tester shows the full match only. It does not list the values of capture groups, so check your groups in code with match() or matchAll(), which return each group in the result array. Getting the groups right matters for log parsing, data extraction, and search-and-replace operations where the replacement references captured groups.

Backreferences let you match the same text that was captured earlier. The pattern (["']).*?\1 matches a string enclosed in matching quotes (either single or double). The \1 refers to whatever the first group captured, so if the opening quote was ", the closing quote must also be ".

Lookahead and Lookbehind

Lookahead assertions match a pattern only if it is followed by (or not followed by) another pattern. (?=...) is a positive lookahead, and (?!...) is a negative lookahead. For example, \d+(?= dollars) matches digits only when followed by the text " dollars" but does not include " dollars" in the match. The match is just the digits.

Lookbehind assertions work the same way but look backward. (?<=\$)\d+ matches digits preceded by a dollar sign. (?<!\d)\d{3}(?!\d) matches exactly three digits not surrounded by other digits.

These are zero-width assertions. They check a condition without consuming characters, so they do not appear in the match result. They are invaluable for complex pattern matching where you need context-dependent matches without including the context in the result.

Password strength validation is a classic lookahead use case. The pattern (?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,} checks that a string has at least one lowercase letter, one uppercase letter, one digit, one special character, and is at least 8 characters long. Each (?=...) is a separate condition that must be true at the current position for the overall match to succeed.

Another practical example: (?<=\bversion )\d+\.\d+\.\d+ extracts version numbers from strings like "version 2.4.1" without including the word "version" in the match.

Regex in Different Languages

JavaScript uses the /pattern/flags syntax: /\d+/g. The RegExp constructor allows dynamic patterns: new RegExp(userInput, 'g'). JavaScript supports lookahead and lookbehind (since ES2018), named groups, and Unicode property escapes (\p{L} for any letter with the u flag).

Python uses the re module: re.findall(r'\d+', text). Python supports all standard features plus verbose mode (re.VERBOSE) that allows comments and whitespace in patterns. Python does not support possessive quantifiers or atomic groups in the standard library.

Java uses java.util.regex: Pattern.compile("\\d+").matcher(text). Note the double backslash because Java string literals interpret backslashes. Java supports possessive quantifiers (\d++) and atomic groups (?>...).

Go uses the regexp package, which implements RE2 syntax. RE2 guarantees linear time matching but does not support backreferences or lookaround. If your pattern uses these features, it will not work in Go.

This tool uses JavaScript's regex engine. Patterns that work here will work in JavaScript, TypeScript, and any environment using V8, SpiderMonkey, or JavaScriptCore. If your target is Python, Java, or another language, test in that language's regex engine too, because there are subtle differences in syntax and behavior.

Common Mistakes with Regular Expressions

Mistake 1: Not escaping special characters. The dot (.) in a regex matches any character. If you want to match a literal period (like in a filename or IP address), you must escape it: \. instead of just a bare dot. The pattern 192.168.1.1 matches 192X168Y1Z1 because each dot matches any character. Use 192\.168\.1\.1 for a literal IP address.

Mistake 2: Greedy vs. lazy quantifiers. By default, * and + are greedy and match as much text as possible. The pattern <.*> applied to "<b>bold</b>" matches the entire string "<b>bold</b>", not just "<b>". This happens because .* grabs everything it can, then backtracks. Use <.*?> (lazy) to match the shortest possible string, which gives "<b>" and "</b>" separately.

Mistake 3: Forgetting anchors. The pattern \d{3} matches any three consecutive digits anywhere in the string, including substrings of longer numbers. 12345 produces two matches: 123 and 45 (with the g flag and overlapping not enabled, you get 123 and then the engine continues from position 3). If you want to match exactly three digits and nothing more, use ^\d{3}$ with anchors.

Mistake 4: Catastrophic backtracking. Patterns like (a+)+ or (a|aa)* can cause the regex engine to explore an exponential number of paths on certain inputs. The string "aaaaaaaaaaaaaab" against (a+)+ takes billions of steps because the engine tries every way to partition the a's between the inner and outer quantifiers before concluding there is no match. This makes your application hang or crash. Avoid nested quantifiers on overlapping patterns. If you see your regex taking a long time on certain inputs, backtracking is the likely cause.

Mistake 5: Assuming regex syntax is universal. JavaScript does not support possessive quantifiers (a++), atomic groups ((?>...)), or conditional patterns. PCRE (used in PHP and many tools) supports these. Python's re module does not support possessive quantifiers either, but the regex module (third-party) does. If you copy a pattern from a PHP or Perl example, it may not work in JavaScript. This tool uses JavaScript's regex engine, so test here if your target environment is JavaScript.

Mistake 6: Trying to parse nested structures with regex. Regular expressions fundamentally cannot match balanced brackets, nested HTML tags, or recursive grammar. A regex to match all opening and closing div tags in nested HTML will fail on edge cases. Use a proper parser (DOM parser for HTML, JSON.parse for JSON, a programming language parser for code).

Advanced Tips

Use \b for word boundary matching to avoid partial matches. Searching for cat without boundaries matches "cat" inside "concatenate" and "education". Using \bcat\b matches only the standalone word "cat".

When building complex patterns, work incrementally. Start with the simplest pattern that matches part of your target, test it, then add complexity. Do not write a 200-character regex in one go. The tester's real-time feedback makes this incremental approach natural and fast.

For multiline log parsing, enable the m flag and use ^ and $ to match line boundaries. The pattern ^ERROR.*$ with the gm flags will match every line that starts with ERROR. Without the m flag, ^ only matches the start of the entire text.

Use regex comments in languages that support verbose mode. In Python, re.compile(r''' (\d{4}) # year - # separator (\d{2}) # month - # separator (\d{2}) # day ''', re.VERBOSE) makes complex patterns readable. JavaScript does not support verbose mode natively, but you can build patterns by concatenating strings with comments.

For performance-critical code, precompile your regex outside of loops. In JavaScript, create the RegExp object once: const pattern = /\d+/g; and reuse it. In Java, compile the Pattern once and create new Matcher instances. Compiling a regex inside a loop wastes CPU cycles.

When replacing matched text, capture groups let you rearrange and transform content. In JavaScript, 'John Smith'.replace(/(\w+) (\w+)/, '$2, $1') produces 'Smith, John'. In Python, re.sub(r'(\w+) (\w+)', r'\2, \1', 'John Smith') does the same. Named groups work too: ${name} in JavaScript replacements.

Regex for Data Validation

Form validation is one of the primary uses of regex in web development. You validate user input against patterns before submitting to the server.

Credit card numbers follow specific patterns by card type: Visa starts with 4 and has 13 or 16 digits (4\d{12}(\d{3})?), Mastercard starts with 51-55 or 2221-2720 (5[1-5]\d{14}|2[2-7]\d{14}), and American Express starts with 34 or 37 and has 15 digits (3[47]\d{13}). After matching the pattern, validate the number with the Luhn algorithm in code. Regex catches format errors, but the checksum catches digit errors.

Postal codes vary by country: US ZIP codes match \d{5}(-\d{4})? for standard and ZIP+4 formats. Canadian postal codes match [A-Za-z]\d[A-Za-z] \d[A-Za-z]\d. UK postcodes are more complex: [A-Z]{1,2}\d[A-Z\d]? \d[A-Z]{2}. German PLZ are simply \d{5}.

Semantic version numbers (semver) match (0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)?(\+[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)*)? which captures major, minor, patch, pre-release, and build metadata groups.

Slug validation for URLs: ^[a-z0-9]+(-[a-z0-9]+)*$ ensures a URL-friendly string of lowercase letters, digits, and hyphens that does not start or end with a hyphen.

UUID (version 4) matching: [0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12} with the i flag matches UUIDs like 550e8400-e29b-41d4-a716-446655440000. The 4 in the third group and [89ab] in the fourth group are specific to version 4.

Regex for Text Processing

Beyond validation, regex is used heavily for text extraction and transformation.

Removing HTML tags: <[^>]+> matches any HTML tag. Replace all matches with an empty string to strip tags from HTML content. This is a rough approach that works for simple HTML but fails on edge cases like > inside attributes or script tags containing > in string literals.

Extracting data from structured text: if you have log lines like [2026-03-21 14:30:05] user=alice action=login ip=192.168.1.1, the pattern (\w+)=(\S+) with the g flag extracts all key-value pairs. Each match gives you the key in group 1 and the value in group 2.

CamelCase to kebab-case conversion: first replace ([A-Z]) with -$1, then lowercase the result. The regex identifies each uppercase letter and inserts a hyphen before it. So backgroundColor becomes background-color.

Finding duplicate words: \b(\w+)\s+\1\b matches repeated words like "the the" or "is is". The \1 backreference matches the same word captured in group 1. This is useful for proofreading.

CSV parsing with quoted fields: handling commas inside quoted strings requires a pattern like (?:"([^"]*(?:""[^"]*)*)"|([^,]+)|(?<=,)(?=,)) which accounts for escaped quotes within quoted fields. In practice, use a dedicated CSV parser, but understanding this regex teaches you about non-greedy matching and alternation.

Regex Performance

Regular expressions can be fast or catastrophically slow depending on the pattern and input. Understanding performance helps you write patterns that work reliably in production.

Linear time patterns: patterns without backreferences, lookaround, or nested quantifiers run in O(n) time where n is the input length. Most practical patterns fall in this category.

Backtracking patterns: when the regex engine tries one path and fails, it backtracks to try another. Simple backtracking is fine. Nested quantifiers like (a+)+ create exponential backtracking on non-matching inputs. The string "aaaaab" against (a+)+b is fine (it matches), but "aaaaaX" causes the engine to explore 2^n paths before concluding no match exists.

To avoid performance problems: avoid nested quantifiers on the same characters, use atomic groups or possessive quantifiers where available, and test your regex against non-matching inputs (which is when backtracking is worst). If your target is JavaScript, where atomic groups are not available, restructure the pattern to avoid ambiguity. For example, instead of (a+)+, use a+ which has the same matching behavior without the nested group.

Benchmark your regex on realistic inputs. A pattern that works fine on 100-character test strings might timeout on 10,000-character production inputs if it has backtracking potential.

Frequently asked questions

Which language does it use?

It uses the JavaScript RegExp engine built into your browser. Patterns behave as they do in JavaScript and TypeScript. Python, Java, PHP, and Go differ in some syntax, so test there too.

Does it support complex patterns?

Yes. It handles lookaheads, lookbehinds, named groups, and other advanced patterns.

Related guides

Related WebRecast sections