How to Test Regular Expressions
Regular expressions (regex) are powerful for pattern matching, but they can be tricky to get right. This tutorial shows you how to test regex patterns using online tools, browser console, and JavaScript code—plus common patterns for validation.
Why Test Regular Expressions?
Regex bugs are subtle and hard to debug. Testing helps you:
- ✅ Verify patterns match expected input
- ✅ Catch edge cases early
- ✅ Visualize match groups
- ✅ Debug greedy vs. lazy matching
- ✅ Test against multiple test cases
Method 1: Online Regex Testers
Top Tools
| Tool | Features | Best For | |------|----------|----------| | Regex101 | regex101.com | Detailed explanations | | RegExr | regexr.com | Interactive learning | | Regex Storm | regexstorm.net | .NET regex testing | | MyRegexTool | myregextool.com | Quick testing |
Using Regex101
1. Go to regex101.com 2. Select flavor (JavaScript, Python, etc.) 3. Enter your regex pattern 4. Add test strings 5. Review match results and explanations
Features:
- Real-time matching
- Match group visualization
- Pattern explanation
- Shareable links
- Regex cheat sheet
Method 2: Browser Console Testing
Quick testing without leaving your browser:
// Create a regex
const regex = /^\d{3}-\d{3}-\d{4}$/;// Test a string
regex.test('123-456-7890');
// true
regex.test('1234567890');
// false
// Get all matches
const text = 'Call 123-456-7890 or 098-765-4321';
const matches = text.match(/\d{3}-\d{3}-\d{4}/g);
console.log(matches);
// ['123-456-7890', '098-765-4321']
Testing with Match Groups
const emailRegex = /^(\w+)@(\w+\.\w+)$/;
const result = emailRegex.exec('[email protected]');console.log(result);
// ['[email protected]', 'user', 'example.com', index: 0, input: '[email protected]', groups: undefined]
console.log(result[0]); // Full match: '[email protected]'
console.log(result[1]); // Group 1: 'user'
console.log(result[2]); // Group 2: 'example.com'
Named Capture Groups
const dateRegex = /(?\d{4})-(?\d{2})-(?\d{2})/;
const result = dateRegex.exec('2026-03-11');console.log(result.groups);
// { year: '2026', month: '03', day: '11' }
Method 3: JavaScript Regex Tester Function
function testRegex(pattern, testStrings, flags = 'g') {
const regex = new RegExp(pattern, flags);
const results = []; for (const str of testStrings) {
const match = str.match(regex);
results.push({
input: str,
matched: match !== null,
matches: match || [],
groups: match?.groups || null
});
}
return {
pattern,
flags,
results
};
}
// Usage
const emailPattern = '^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}