How to Test Regular Expressions

Learn how to test regular expressions with online tools and JavaScript. Complete guide with regex debugging, testing patterns, and validation examples.

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,}

🚀 Deploy Your Own Tools — Recommended Hosting

Want to self-host or build your own developer tools? These are the platforms we use:

🌐
Hostinger
Web Hosting from $2.99/mo
💧
DigitalOcean
$200 Free Credit for New Users
🔑
Namecheap
Domains from $0.99/yr

* Affiliate links — we may earn a commission at no extra cost to you.

🔥 Limited Time Offer — Starting at $5

Get instant access to premium developer tools — exclusive discount ends soon!

🔒 安全支付 via Gumroad | 即时下载

; const testCases = [ '[email protected]', '[email protected]', 'invalid-email', '@example.com', 'user@' ];

const results = testRegex(emailPattern, testCases); console.table(results.results.map(r => ({ Input: r.input, Matched: r.matched })));

Method 4: Interactive HTML Tester




  Regex Tester
  


  

Regex Tester

Common Regex Patterns for Validation

Email Validation

const emailRegex = /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/;

emailRegex.test('[email protected]'); // true emailRegex.test('invalid'); // false

Phone Number (US Format)

// Matches: 123-456-7890, (123) 456-7890, 1234567890
const phoneRegex = /^(\+1)?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;

phoneRegex.test('123-456-7890'); // true phoneRegex.test('(123) 456-7890'); // true

URL Validation

const urlRegex = /^https?:\/\/(www\.)?[\w.-]+\.[a-z]{2,}(\/[\w.-])\/?$/i;

urlRegex.test('https://example.com'); // true urlRegex.test('http://sub.domain.org/path'); // true

Password Strength

// At least 8 chars, 1 uppercase, 1 lowercase, 1 number, 1 special char
const passwordRegex = /^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[@$!%?&])[A-Za-z\d@$!%?&]{8,}$/;

passwordRegex.test('SecureP@ss1'); // true passwordRegex.test('weak'); // false

Credit Card (Luhn algorithm not included)

// Matches common formats: 1234567890123456, 1234-5678-9012-3456
const ccRegex = /^\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}$/;

ccRegex.test('1234-5678-9012-3456'); // true

Date (YYYY-MM-DD)

const dateRegex = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;

dateRegex.test('2026-03-11'); // true dateRegex.test('2026-13-01'); // false (invalid month)

Regex Debugging Tips

1. Test Incrementally

Build complex regex step by step:

// Start simple
/\d+/; // Match digits

// Add constraints /^\d+$/; // Only digits

// Add specific length /^\d{10}$/; // Exactly 10 digits

// Add formatting /^\d{3}-\d{3}-\d{4}$/; // Phone format

2. Use Character Classes

// Instead of this:
/[0-9a-zA-Z_]/

// Use this: /\w/

// Instead of this: /[0-9]/

// Use this: /\d/

3. Beware of Greedy Matching

const text = '
Hello
World
';

// Greedy (matches too much) text.match(/

.<\/div>/); // ['
Hello
World
']

// Lazy (matches correctly) text.match(/

.?<\/div>/g); // ['
Hello
', '
World
']

4. Escape Special Characters

function escapeRegex(string) {
  return string.replace(/[.+?^${}()|[\]\\]/g, '\\{{ content | safe }}');
}

// Usage const userInput = 'hello.world'; const regex = new RegExp(escapeRegex(userInput)); // Matches literal "hello.world", not "helloXworld"

Complete Regex Testing Utility

class RegexTester {
  constructor(pattern, flags = 'g') {
    this.pattern = pattern;
    this.flags = flags;
    this.regex = new RegExp(pattern, flags);
  }

test(string) { return this.regex.test(string); }

match(string) { return string.match(this.regex); }

matchAll(string) { return [...string.matchAll(this.regex)]; }

replace(string, replacement) { return string.replace(this.regex, replacement); }

validate(testCases) { return testCases.map(({ input, expected }) => ({ input, expected, actual: this.test(input), passed: this.test(input) === expected })); }

explain() { // Basic pattern explanation const explanations = { '\\d': 'digit', '\\w': 'word character', '\\s': 'whitespace', '.': 'any character', '': '0 or more', '+': '1 or more', '?': '0 or 1', '^': 'start of string', '

: 'end of string' };

return this.pattern.split('').map(c => explanations[c] || c).join(' '); } }

// Usage const emailTester = new RegexTester('^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}

);

console.log(emailTester.test('[email protected]')); // true

console.log(emailTester.match('Contact: [email protected]')); // ['[email protected]']

const testCases = [ { input: '[email protected]', expected: true }, { input: 'invalid', expected: false }, { input: '@example.com', expected: false } ];

console.table(emailTester.validate(testCases));

Try It Online

Need to test regex quickly? Use our Regex Tester for instant pattern testing with highlighting and match groups.

Conclusion

Test regex patterns before deploying them. Use online tools like Regex101 for complex patterns, browser console for quick tests, and the RegexTester class for automated validation. Always test edge cases.

For more developer tools, visit DevKits.

---

Related Tools:

🔥 Limited Time Offer — Starting at $5

Get instant access to premium developer tools — exclusive discount ends soon!

🛠️

AI 工具数据库

82 个开发者工具离线版

👥 50+ developers purchased

$9 立即获取 →
📝

SEO 内容包

100 篇开发者文章

👥 30+ developers purchased

$19 立即获取 →
💎

空投狩猎指南 2026

从零成本到高级技巧

👥 25+ developers purchased

$5 立即获取 →

🔒 安全支付 via Gumroad | 即时下载