Regex Tester
还没有匹配结果
输入正则与文本后,这里会展示每个匹配、捕获组和命名分组。
统计
命名分组汇总
当前没有命名分组。
Free online Regex Tester with JS real-time matching, Capture Group/Named Group inspection, replace preview, regex syntax explanation. Built-in Web Worker ReDoS timeout protection, common regex template library included. Ideal for developers to quickly debug and validate regular expressions.
Related
What is a Regular Expression (Regex/RegExp)?
Regular Expression (abbreviated Regex/RegExp) is a text pattern language that uses a single string to describe and match a series of strings conforming to certain syntactic rules. Its history dates back to the 1950s when neuroscientist Warren McCulloch and mathematician Walter Pitts proposed a mathematical model of neurons; later mathematician Stephen Kleene built on this in 1956 to describe "regular sets" algebraically. Ken Thompson, father of Unix, first implemented regular expressions in the QED editor in the late 1960s, after which regex became a core feature of the Unix toolchain (grep, sed, awk, vi).
In modern programming languages, regular expressions are nearly ubiquitous — JavaScript's RegExp, Python's re module, Java's java.util.regex, .NET's Regex class, Go's regexp package all provide regex support. Regex is widely used in form validation (email/phone/ID), text search & replace (editor find/replace), log analysis (ERROR log extraction), web scraping (HTML content extraction), data cleaning (ETL), route matching, input filtering, and security (WAF rules).
Core regex concepts include: character classes (\d digit, \w word char, \s whitespace), quantifiers (* zero or more, + one or more, ? zero or one, {n,m} specified times), anchors (^ start, $ end, \b word boundary), groups ((...) capture group, (?:...) non-capture group, (?<name>...) named group), alternation (|), character sets ([a-z]), lookaround ((?=...) positive lookahead, (?!...) negative lookahead), etc. Mastering regex can greatly improve text processing efficiency, but watch out for performance pitfalls like ReDoS.
Use Cases
- Testing form validation rules online — verify email, phone, ID number, URL regexes work correctly
- Log analysis — using regex to extract timestamps, error messages, IP addresses from ERROR/INFO level logs
- Data cleaning/ETL — preview regex replace effects, e.g. date format conversion, sensitive data masking (phone middle digits asterisked)
- Web scraping — verify content extraction regexes accurately match target HTML fragments or JSON fields
- Learning regex — understand metacharacters and quantifiers through the "Explain" panel, get started quickly with templates
- Code Review — share questionable regexes via link with colleagues for collaborative debugging and optimization
How to Use
- Enter your regex pattern in the input box between / / (no need to add slashes yourself), enter flags on the right (e.g. g, gi, gim) or toggle using the buttons below
- Paste or type text to match in the "Test Text" area — match results will be color-highlighted in real time
- Click the "Match Details" panel on the right to see each match's position, content, Capture Groups and Named Groups
- Switch to the "Replace" tab, enter a replacement string (supports $1/$&/$<name> references), preview replacement results in real time
- Switch to the "Pattern Explain" tab to view auto-generated element-by-element regex syntax explanation
- When you need common templates, click "Template Library" on the left to select and fill instantly; after debugging, click "Share" to generate a link
Features
- Web Worker sandbox execution: Regex runs in an isolated Worker thread with 500ms timeout auto-interrupt, completely preventing ReDoS browser freezes
- Real-time matching + color highlighting: Match results appear instantly as you type, different matches highlighted in 5 colors, hover links to detail panel
- Capture Groups + Named Groups: Each match automatically expands to show all Capture Groups ($1/$2) and Named Groups ($<name>), with summary statistics
- Replace preview: Enter a replacement string to see real-time preview, supports $1/$&/$`/$'/$<name> syntax with quick buttons
- Regex syntax explanation: Automatically parses regex patterns and explains metacharacters, quantifiers, groups, anchors element by element
- 12 common templates: Built-in high-frequency regex templates for email/URL/phone/Chinese/IPv4/UUID/date/log/HTML tags, fill with one click
- 6 flag toggles: g/i/m/s/u/y flag visual toggle buttons, no need to memorize syntax
- Share links: One-click generate URL containing pattern/flags/text, copy to colleagues to reproduce exact test state
- Execution statistics: Real-time display of match count, execution time (ms), total Capture Groups, Named Group count
- 1500 match limit: Auto-truncate to prevent page lag from extremely long text, friendly syntax error hints for invalid regex
Code Examples
Regex Matching & Replacement in JavaScript
// Validate email format
const emailRe = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailRe.test('user@example.com')); // true
// Extract Named Groups (date parsing)
const dateRe = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;
const text = 'Meeting: 2026-03-12, Deadline: 2026-04-01';
const matches = [...text.matchAll(dateRe)];
for (const m of matches) {
console.log(m.groups.year, m.groups.month, m.groups.day);
}
// Replace: date format conversion YYYY-MM-DD → MM/DD/YYYY
const reformatted = text.replace(dateRe, '$<month>/$<day>/$<year>');
console.log(reformatted);
// Meeting: 03/12/2026, Deadline: 04/01/2026Using Python's re Module
import re
# Find all matches
text = 'Contact: alice@example.com, bob@test.org'
emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)
print(emails) # ['alice@example.com', 'bob@test.org']
# Named Group extraction (Python uses ?P<name> syntax)
date_pattern = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
m = re.search(date_pattern, 'Published on 2026-03-12')
if m:
print(m.group('year'), m.group('month'), m.group('day'))
# Replace: mask middle 4 digits of phone number
phone_re = r'(1[3-9]\d)\d{4}(\d{4})'
result = re.sub(phone_re, r'\1****\2', 'Phone: 13812345678')
print(result) # Phone: 138****5678Using java.util.regex in Java
import java.util.regex.*;
class RegexDemo {
public static void main(String[] args) {
String text = "Error [2026-03-12 18:05:09] Connection failed";
// Compile regex (cache Pattern instances in production)
Pattern p = Pattern.compile(
"(?<level>INFO|WARN|ERROR)\\s+\\[(?<time>[^\\]]+)\\]\\s+(?<message>.+)"
);
Matcher m = p.matcher(text);
if (m.find()) {
System.out.println("Level: " + m.group("level"));
System.out.println("Time: " + m.group("time"));
System.out.println("Message: " + m.group("message"));
}
// Replace all digits
String cleaned = "abc123def456".replaceAll("\\d+", "*");
System.out.println(cleaned); // abc*def*
}
}FAQ
What is ReDoS? Why does regex testing need ReDoS protection?
ReDoS (Regular Expression Denial of Service) occurs when maliciously crafted regex patterns (such as `(a+)+$` matching long strings) trigger catastrophic backtracking, causing 100% CPU usage, browser freeze, or server crash. This tool executes regex matching in a Web Worker sandbox with a 500ms timeout that automatically interrupts execution. Even malicious regexes that trigger backtracking won't freeze your browser — this is our core security feature.
What do the six flags g, i, m, s, u, y mean in regular expressions?
g (global) finds all matches instead of the first; i (ignoreCase) makes matching case-insensitive; m (multiline) makes ^ and $ match the start/end of each line; s (dotAll) makes dot . match all characters including newlines; u (unicode) enables Unicode mode for correct handling of emoji and multi-byte characters; y (sticky) matches exactly from the lastIndex position. This tool provides visual toggle buttons for all six flags — click to enable/disable in real time.
What are Capture Groups and Named Groups? How to use them?
Capture Groups are wrapped in parentheses `(pattern)`; after matching, you can reference extracted substrings via $1, $2, etc. Named Groups use the `(?<name>pattern)` syntax and can be referenced via `$<name>` after matching for better code readability. For example, after matching a date with `(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})`, you can reformat it in the replacement string as `$<year>/$<month>/$<day>`. This tool automatically lists Capture Group and Named Group results for each match.
Which programming language regex syntaxes are supported?
This tool is based on JavaScript's native RegExp engine, which is largely compatible with mainstream engines like JS/TypeScript, Python re module, Java java.util.regex, PHP preg_*, Go regexp (all based on the PCRE/Perl family). Differences exist in some advanced features (such as Python's `(?P<name>)` named group syntax, .NET's variable-length lookbehind). 99% of regexes used in daily development (email, phone, URL, date validation/extraction) work across engines — you can test here and copy directly into your code.
How do I share a tested regex with colleagues?
Click the "Share" button in the top toolbar — the tool automatically encodes the current regex pattern, flags, and test text into URL parameters and copies the link to your clipboard. When colleagues open the link, they see the exact same test state (pattern+flags+testText), perfect for team collaboration and remote debugging.
What do the special symbols $1, $&, $`, $' mean in replacement strings?
In replacement strings: $1, $2... represent the Nth Capture Group; $& represents the entire matched text; $` represents the text before the match; $' represents the text after the match; $$ represents a literal $; $<name> represents a Named Group. For example, replacing `(\d{4})-(\d{2})-(\d{2})` with `$2/$3/$1` converts 2026-03-12 to 03/12/2026. The replace panel provides quick-insert buttons for these special symbols.
Glossary
- Regex / RegExp
- Short for Regular Expression, a string syntax describing text matching patterns used for searching, replacing, and validating text.
- Capture Group
- A subexpression wrapped in parentheses (pattern), match results can be referenced by position via $1, $2.
- Named Group
- A Capture Group defined with the (?<name>pattern) syntax, can be referenced by name via $<name>, offering better readability than numeric references.
- ReDoS
- Regular Expression Denial of Service, where catastrophic backtracking causes exponential regex execution time, freezing browsers or servers.
- Backtracking
- The mechanism where NFA regex engines fall back to previous positions to try alternatives when a match attempt fails; complex patterns can cause exponential backtracking.
- Flags
- Parameters that modify regex matching behavior; common ones are g(global), i(ignore case), m(multiline), s(dotAll), u(Unicode), y(sticky).
- Lookaround
- Zero-width assertions including positive lookahead (?=...), negative lookahead (?!...), positive lookbehind (?<=...), negative lookbehind (?<!...), which check position without consuming characters.
- PCRE
- Perl Compatible Regular Expressions, a widely used regex syntax standard adopted by PHP, Java, Python, and most other languages.
- Web Worker
- A browser API providing background threads separate from the main thread; this tool uses it to execute regex in a Worker so ReDoS doesn't block the UI.
- Quantifier
- Syntax specifying how many times the preceding element repeats: *(0 or more), +(1 or more), ?(0 or 1), {n}(exactly n), {n,m}(n to m times).
Regex Metacharacter Quick Reference
| Metachar | Meaning | Example |
|---|---|---|
. | Any single character (except newline; includes newline with s flag) | a.c matches abc, aXc, not a\nc |
\d | Digit character, equivalent to [0-9] | \d{3} matches 123, 456 |
\w | Word character, equivalent to [A-Za-z0-9_] | \w+ matches hello_123 |
\s | Whitespace (space/tab/newline etc.) | a\sb matches a b (space between) |
^ | String start (line start with m flag) | ^Hello matches Hello at line start |
$ | String end (line end with m flag) | end$ matches end at line end |
\b | Word boundary | \bcat\b matches standalone cat, not category |
* | Preceding element repeats 0 or more times (greedy) | ab*c matches ac, abc, abbc |
+ | Preceding element repeats 1 or more times | ab+c matches abc, abbc, not ac |
? | Preceding element 0 or 1 time (or used for non-greedy/lookaround) | colou?r matches color and colour |
| | Alternation/OR, matches left or right | cat|dog matches cat or dog |
[...] | Character set, matches any one character within | [aeiou] matches any vowel letter |
Common Regex Template Quick Reference
| Purpose | Regex Pattern | Flags |
|---|---|---|
| Email address | [a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,} | g |
| China Mainland mobile phone | 1[3-9]\d{9} | g |
| URL link | https?:\/\/[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b[-a-zA-Z0-9()@:%_+.~#?&/=]* | gi |
| IPv4 address | \b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b | g |
| Date YYYY-MM-DD | \d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]) | g |
| China ID number (18 digits) | [1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx] | g |
| UUID | [0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12} | gi |
Authoritative References
- Color Blind Simulator
- Color Converter
- .htaccess to Nginx Converter
- SQL Converter
- Cookie Parser
- Cron Expression Generator
- Cron Expression Validator
- CSS Formatter
- CSS Minifier
- CSV to Excel
- CSV Viewer
- CSV Editor
- Currency Converter
- Diff Checker
- Excel to CSV
- Favicon Generator
- CSS Formatter
- HTML Formatter
- Markdown Formatter
- XML Formatter
- Hexadecimal Converter
- HTML Formatter
- HTML Minifier
- HTML to Markdown
- Markdown to HTML
- JavaScript Formatter
- JS Minifier
- JSX Formatter
- JSX Minifier
- Keyword clustering
- Lorem Ipsum Generator
- Markdown Table Generator
- Meta Tag Generator
- Password Generator
- Password Strength Checker
- QR Code & Barcode Generator
- Regex Tester
- Slug Generator
- SQL Builder
- SQL Formatter
- Word Counter
- Text Translator
- Time Tools
- TS Formatter
- TS Minifier
- TSX Formatter
- TSX Minifier
- Unix Timestamp Converter
- UUID Generator
- YAML Formatter
- Case Converter