Regex Validator
Validate regular expression syntax before using patterns in your code. Catch errors like unbalanced brackets, invalid escapes, and unsupported syntax.
Common Regex Syntax Errors
| Error | Cause | Fix |
|---|---|---|
| Unmatched ( | Missing closing parenthesis | Add ) or escape \\( |
| Unmatched [ | Missing closing bracket | Add ] or escape \\[ |
| Invalid escape | \\z (not valid) | Use valid escapes or literal |
| Nothing to repeat | *+ at start | Put character before quantifier |
| Invalid range | [z-a] (backwards) | Use [a-z] |
| Unbalanced } | {3 without } | Complete {3} or escape \\{ |
Regex Validator Implementation
``javascript
function validateRegex(pattern, flags = '') {
const result = {
pattern,
flags,
valid: false,
error: null,
warnings: []
};
try {
// Test compilation
new RegExp(pattern, flags);
result.valid = true;
// Check for common issues (warnings, not errors)
if (pattern.includes('.*') && !pattern.includes('.*?')) {
result.warnings.push('Greedy .* may match more than intended');
}
if (pattern === '' || pattern === '.*' || pattern === '.+') {
result.warnings.push('Pattern is very broad - may match too much');
}
if (!/[\\^$]/.test(pattern) && pattern.length < 3) {
result.warnings.push('Short pattern without anchors may have many matches');
}
// Check for catastrophic backtracking patterns
if (/\(.*\+\)\+|\(.*\*\)\+|\(.*\*\)\*/.test(pattern)) {
result.warnings.push('Potential catastrophic backtracking (nested quantifiers)');
}
} catch (e) {
result.valid = false;
result.error = e.message;
}
return result;
}
// Examples
validateRegex('[a-z]+'); // valid: true
validateRegex('[a-z'); // valid: false, error: "Unterminated character class"
validateRegex('(hello'); // valid: false, error: "Unmatched '('"
``
Valid Escape Sequences
| Escape | Meaning | Escape | Meaning |
|---|---|---|---|
| \\d | Digit | \\D | Non-digit |
| \\w | Word char | \\W | Non-word |
| \\s | Whitespace | \\S | Non-space |
| \\b | Word boundary | \\B | Non-boundary |
| \\n | Newline | \\t | Tab |
| \\. | Literal dot | \\\\ | Literal backslash |
Browser vs Node.js Differences
| Feature | Browser | Node.js |
|---|---|---|
| Lookbehind (?<=) | Modern browsers | v8.10+ |
| Named groups (?) | Modern browsers | v10+ |
| Unicode property \\p{} | Modern browsers | v10+ |
| Sticky flag /y | All modern | v6+ |