Regex Replace Tester
Test regex search-and-replace rules with flags and preview the transformed output instantly.
Back to all tools on ToolForge
Output
About Regex Replace Tester
This regex replace tester lets you try search-and-replace rules with JavaScript-compatible regular expressions. It supports all standard regex flags (g, i, m, s, u, y) and replacement patterns including capture group references. The tool validates patterns and displays errors for invalid regex syntax.
It is useful for bulk text cleanup, rewrite rules, log parsing and cleanup, code refactoring, data transformation, URL rewriting, and verifying replacement logic before applying it in production code.
Regular Expression Basics
Regular expressions are patterns that describe text for searching and manipulation:
Regex Components:
1. Literal Characters
- Match themselves exactly
- Example: /hello/ matches "hello"
2. Metacharacters (special meaning)
. - Any character except newline
* - 0 or more of previous
+ - 1 or more of previous
? - 0 or 1 of previous
^ - Start of string/line
$ - End of string/line
[] - Character class
() - Capture group
| - Alternation (OR)
{} - Quantifier
\ - Escape character
3. Character Classes
\d - Digit [0-9]
\D - Non-digit [^0-9]
\w - Word character [a-zA-Z0-9_]
\W - Non-word character
\s - Whitespace (space, tab, newline)
\S - Non-whitespace
\b - Word boundary
\B - Non-word boundary
Example Pattern:
Pattern: /\b(\w+)\s+\1\b/g
Purpose: Find repeated words
Matches: "the the", "hello hello"
Regex Flags Reference
| Flag | Name | Description | Example |
|---|---|---|---|
| g | Global | Replace all matches, not just first | /a/g replaces all "a" |
| i | Ignore Case | Case-insensitive matching | /A/i matches "a" or "A" |
| m | Multiline | ^ and $ match line boundaries | /^test/m matches line starts |
| s | DotAll | Dot matches newlines too | /.*?/s matches across lines |
| u | Unicode | Unicode-aware matching | /\p{L}/u matches letters |
| y | Sticky | Match at position only | /a/y matches at lastIndex |
Replacement Pattern Syntax
Replacement Sequences: $& - Entire matched string $` - String before the match $' - String after the match $$ - Literal $ character $1-$9 - Capture group 1-9 $- Named capture group Examples: Input: "John Doe" Pattern: /(\w+) (\w+)/ Replace: "$2, $1" Result: "Doe, John" Input: "hello world" Pattern: /(\w+)/g Replace: "[$&]" Result: "[hello] [world]" Input: "abc123def" Pattern: /(\d+)/ Replace: "($`)|$&|($')" Result: "(abc)|123|(def)" Named Groups: Input: "2024-03-15" Pattern: /(? \d{4})-(? \d{2})-(? \d{2})/ Replace: "$ /$ /$ " Result: "03/15/2024" Escaping: Input: "Price: $100" Pattern: /\$(\d+)/ Replace: "$$${1}.00" Result: "Price: ${100}.00"
Common Regex Patterns
| Pattern | Description | Example Match |
|---|---|---|
| \b\w+@\w+\.\w+\b | Basic email | [email protected] |
| https?://\S+ | URLs | https://example.com/path |
| \b\d{3}-\d{4}\b | Phone (xxx-xxxx) | 555-1234 |
| \b[A-Z][a-z]+ [A-Z][a-z]+\b | Name (First Last) | John Doe |
| \s+ | Whitespace | Spaces, tabs, newlines |
| <[^>]*> | HTML tags | <div class="x"> |
| \b(\w+)\s+\1\b | Repeated words | the the |
| ^\s*#.* | Comment lines | # This is a comment |
Code Examples by Language
JavaScript:
// Basic replace
text.replace(/pattern/g, 'replacement')
// With capture groups
text.replace(/(\w+) (\w+)/, '$2, $1')
// With function
text.replace(/\d+/g, (m) => `[${m}]`)
// Using RegExp object
const regex = new RegExp(pattern, flags);
text.replace(regex, replacement);
Python:
import re
# Basic replace
re.sub(r'pattern', 'replacement', text)
# With capture groups
re.sub(r'(\w+) (\w+)', r'\2, \1', text)
# With function
re.sub(r'\d+', lambda m: f'[{m.group()}]', text)
# Count replacements
result, count = re.subn(r'pattern', 'rep', text)
PHP:
// Basic replace
preg_replace('/pattern/', 'replacement', $text)
// With capture groups
preg_replace('/(\w+) (\w+)/', '$2, $1', $text)
// With function
preg_replace_callback('/\d+/', fn($m) => "[{$m[0]}]", $text)
// Limit replacements
preg_replace('/pat/', 'rep', $text, 1)
Java:
// Basic replace
text.replaceAll("pattern", "replacement")
// With capture groups
text.replaceAll("(\\w+) (\\w+)", "$2, $1")
// Using Pattern
Pattern.compile("pattern").matcher(text).replaceAll("rep")
C#:
// Basic replace
Regex.Replace(text, "pattern", "replacement")
// With capture groups
Regex.Replace(text, @"(\w+) (\w+)", "$2, $1")
// With function
Regex.Replace(text, @"\d+", m => $"[{m.Value}]")
Regex Replace Examples
Example 1: Simple Word Replacement
Pattern: hello
Replace: hi
Input: "hello world, hello there"
Output (g): "hi world, hi there"
Output (no g): "hi world, hello there"
Example 2: Case-Insensitive Replace
Pattern: hello
Flags: gi
Replace: HI
Input: "Hello HELLO hello"
Output: "HI HI HI"
Example 3: Swap Words Using Capture Groups
Pattern: (\w+) (\w+)
Replace: $2 $1
Input: "John Doe, Jane Smith"
Output: "Doe John, Smith Jane"
Example 4: Remove HTML Tags
Pattern: <[^>]*>
Replace: (empty)
Input: "<p>Hello <b>World</b></p>"
Output: "Hello World"
Example 5: Normalize Whitespace
Pattern: \s+
Replace: " "
Input: "too many\n\nnewlines"
Output: "too many newlines"
Example 6: Format Numbers (add commas)
Pattern: \B(?=(\d{3})+(?!\d))
Replace: ","
Input: "1000000"
Output: "1,000,000"
Example 7: Mask Credit Card
Pattern: \d(?=\d{4})
Replace: "*"
Input: "1234567890123456"
Output: "***********23456"
Example 8: Convert Date Format
Pattern: (\d{4})-(\d{2})-(\d{2})
Replace: $2/$3/$1
Input: "2024-03-15"
Output: "03/15/2024"
Example 9: Remove Comments
Pattern: ^\s*#.*$
Flags: gm
Replace: (empty)
Input: "code\n# comment\nmore"
Output: "code\nmore"
Example 10: URL to Link
Pattern: (https?://\S+)
Replace: <a href="$1">$1</a>
Input: "Visit https://example.com"
Output: "Visit <a href="https://example.com">https://example.com</a>"
Quantifiers Reference
Quantifier | Matches | Example
-------------|------------------|------------------
* | 0 or more /a*/ matches "", "a", "aaa"
+ | 1 or more /a+/ matches "a", "aaa" (not "")
? | 0 or 1 /a?/ matches "" or "a"
{n} | Exactly n /a{3}/ matches "aaa"
{n,} | n or more /a{2,}/ matches "aa", "aaa"
{n,m} | n to m /a{2,4}/ matches "aa", "aaa", "aaaa"
*? | Lazy 0 or more /a*?/ matches minimal
+? | Lazy 1 or more /a+?/ matches minimal
?? | Lazy 0 or 1 /a??/ matches minimal
Greedy vs Lazy:
Greedy (default): Match as much as possible
Lazy (? suffix): Match as little as possible
Example:
Input: "<div>content</div>"
Greedy: /<.*>/ matches "<div>content</div>"
Lazy: /<.*?>/ matches "<div>" then "</div>"
Best Practices
- Test with edge cases: Include empty strings, special characters, and unexpected input formats.
- Use specific patterns: More specific patterns are faster and less error-prone.
- Escape special characters: Remember to escape . * + ? ^ $ { } ( ) | [ ] \ when matching literally.
- Consider performance: Complex patterns on large text can be slow; avoid catastrophic backtracking.
- Use non-capturing groups: Use (?:pattern) instead of (pattern) when you don't need the capture.
- Anchor when possible: Use ^ and $ to anchor patterns for better performance.
- Comment complex regex: Use the x flag (in some languages) or add comments explaining patterns.
Common Mistakes
- Forgetting to escape: Using . when you mean literal dot (matches any char instead).
- Greedy matching issues: Using .* when you need .*? for non-greedy matching.
- Missing global flag: Only first match replaced when all matches needed.
- Wrong character classes: Using \w when you need [a-zA-Z] (underscore included in \w).
- Catastrophic backtracking: Nested quantifiers like (a+)+ can cause exponential time.
- Assuming multiline by default: ^ and $ match string boundaries, not line boundaries without m flag.
- Over-matching: Using .* which can match more than intended across line boundaries.
Frequently Asked Questions
- What are regular expressions and how do they work?
- Regular expressions (regex) are patterns that describe text for searching and manipulation. They consist of literal characters and metacharacters with special meanings. The regex engine matches patterns against input text, finding occurrences for replacement or extraction.
- What do the regex flags mean?
- Common flags: g (global) - replace all matches, not just first; i (ignoreCase) - case-insensitive matching; m (multiline) - ^ and $ match line boundaries; s (dotAll) - dot matches newlines; u (unicode) - Unicode-aware matching; y (sticky) - match at position only.
- How do replacement patterns work?
- Replacement patterns can include literal text and special sequences: $1, $2, etc. for capture groups; $& for entire match; $` for before match; $' for after match; $$ for literal dollar sign. Named groups use $
syntax. - What are common regex metacharacters?
- Common metacharacters: . (any char), * (0+ times), + (1+ times), ? (0 or 1 time), ^ (start), $ (end), [] (character class), () (capture group), | (alternation), {} (quantifier), \ (escape). These form the building blocks of regex patterns.
- How do I escape special characters in regex?
- To match literal special characters, escape them with backslash: \., \*, \+, \?, \[, \], \(\), \{\}, \|, \\. For example, to match 'example.com' literally, use 'example\.com' since unescaped dot matches any character.
- What are capture groups and how do I use them?
- Capture groups (parentheses) extract matched text for reuse. Group 1 is $1, group 2 is $2, etc. Named groups use (?<name>pattern) syntax and $<name> in replacement. Example: /(\w+), (\w+)/ replaced with '$2 $1' swaps 'Doe, John' to 'John Doe'.