Master regular expressions with patterns, optimization, testing, and security for all programming languages.
/plugin marketplace add claudeforge/marketplace/plugin install regex-master@claudeforge-marketplaceMaster regular expressions with patterns, optimization, testing, and security for all programming languages.
// Flags
const flags = {
g: 'global - find all matches',
i: 'case-insensitive',
m: 'multiline - ^ and $ match line boundaries',
s: 'dotall - . matches newlines',
u: 'unicode - proper unicode handling'
};
// Character classes
const patterns = {
digit: /\d/, // [0-9]
word: /\w/, // [a-zA-Z0-9_]
whitespace: /\s/, // [ \t\n\r\f\v]
anyChar: /./, // Any except newline
vowels: /[aeiou]/i,
hexDigit: /[0-9a-fA-F]/
};
// Quantifiers
const quantifiers = {
zeroOrMore: /a*/, // a, aa, aaa, or empty
oneOrMore: /a+/, // a, aa, aaa (not empty)
zeroOrOne: /a?/, // a or empty
exactly: /a{3}/, // aaa (exactly 3)
atLeast: /a{3,}/, // aaa, aaaa, etc.
range: /a{3,5}/ // aaa, aaaa, or aaaaa
};
// Greedy vs lazy
const greedy = /".+"/; // Matches entire: "first" and "second"
const lazy = /".+?"/; // Matches: "first" separately
// Anchors
const anchors = {
startOfString: /^hello/,
endOfString: /world$/,
wordBoundary: /\bcat\b/ // Matches 'cat' but not 'catch'
};
// Email validation
const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const emailRFC = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// URL validation
const url = /^https?:\/\/[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\/[^\s]*)?$/;
// Phone numbers (US)
const phone = /^\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})$/;
const phoneFlexible = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/;
// Date formats
const dateISO = /^\d{4}-\d{2}-\d{2}$/; // YYYY-MM-DD
const dateUS = /^(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])\/\d{4}$/; // MM/DD/YYYY
// Password strength
const password = {
hasUppercase: /[A-Z]/,
hasLowercase: /[a-z]/,
hasDigit: /\d/,
hasSpecial: /[!@#$%^&*(),.?":{}|<>]/,
strong: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/
};
// IP addresses
const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
// Credit cards
const creditCard = {
visa: /^4[0-9]{12}(?:[0-9]{3})?$/,
mastercard: /^5[1-5][0-9]{14}$/,
amex: /^3[47][0-9]{13}$/
};
// Named capture groups
const datePattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = '2024-03-15'.match(datePattern);
console.log(match.groups); // { year: '2024', month: '03', day: '15' }
// Lookahead/lookbehind
const hasUpperAndLower = /^(?=.*[a-z])(?=.*[A-Z]).+$/; // Positive lookahead
const noDigits = /^(?!.*\d).+$/; // Negative lookahead
const afterDollar = /(?<=\$)\d+/; // Positive lookbehind
const notAfterDollar = /(?<!\$)\d+/; // Negative lookbehind
// Non-capturing groups
const urlPattern = /^(?:https?:\/\/)?(?:www\.)?([a-z0-9-]+)\.com$/i;
// Backreferences
const repeatedWord = /\b(\w+)\s+\1\b/; // Matches "hello hello"
const htmlTag = /<(\w+)>(.*?)<\/\1>/; // Matches <div>content</div>
// Alternation
const fileExt = /\.(jpg|jpeg|png|gif|webp)$/i;
// BAD: Catastrophic backtracking
const bad = /^(a+)+$/; // Hangs on: 'aaaaaaaaab'
// GOOD: Avoid nested quantifiers
const good = /^a+$/;
// BAD: Unnecessary capturing groups
const inefficient = /(\d{4})-(\d{2})-(\d{2})/;
// GOOD: Non-capturing when not needed
const efficient = /\d{4}-\d{2}-\d{2}/;
// BAD: Alternation with common prefix
const unoptimized = /hello world|hello there|hello everyone/;
// GOOD: Factor out common prefix
const optimized = /hello (?:world|there|everyone)/;
// Use character classes instead of alternation
const charClass = /[abc]/; // Better than /a|b|c/
// Benchmark regex performance
function benchmarkRegex(pattern, text, iterations = 100000) {
const start = performance.now();
for (let i = 0; i < iterations; i++) pattern.test(text);
return performance.now() - start;
}
// Vulnerable to ReDoS
const vulnerable = /^(a+)+$/;
const vulnerable2 = /(\w+\*)+/;
// Detect dangerous patterns
function isRegexSafe(pattern) {
const dangerousPatterns = [
/(\w+\*)+/, // Nested quantifiers
/(\w+)+/, // Repeated groups
/(\w*)*/ // Nested * quantifiers
];
const patternStr = pattern.toString();
for (const dangerous of dangerousPatterns) {
if (dangerous.test(patternStr)) return false;
}
return true;
}
// Timeout wrapper
function safeRegexTest(pattern, text, timeoutMs = 1000) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('Regex timeout')), timeoutMs);
try {
const result = pattern.test(text);
clearTimeout(timeout);
resolve(result);
} catch (error) {
clearTimeout(timeout);
reject(error);
}
});
}
// Escape user input
function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
# Python
import re
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
email_regex = re.compile(email_pattern)
# Named groups
date_pattern = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
match = re.match(date_pattern, '2024-03-15')
print(match.group('year')) # '2024'
# Find all
text = 'Email: john@example.com or jane@example.com'
emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)
<?php
// PHP
$email_pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
preg_match($email_pattern, $email);
// Named groups
$pattern = '/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/';
preg_match($pattern, '2024-03-15', $matches);
echo $matches['year']; // '2024'
// Replace
$censored = preg_replace('/\b\d{4}\b/', '****', 'My PIN is 1234');
?>
Use this agent when you need to review code for adherence to project guidelines, style guides, and best practices. This agent should be used proactively after writing or modifying code, especially before committing changes or creating pull requests. It will check for style violations, potential issues, and ensure code follows the established patterns in CLAUDE.md. Also the agent needs to know which files to focus on for the review. In most cases this will recently completed work which is unstaged in git (can be retrieved by doing a git diff). However there can be cases where this is different, make sure to specify this as the agent input when calling the agent. Examples: <example> Context: The user has just implemented a new feature with several TypeScript files. user: "I've added the new authentication feature. Can you check if everything looks good?" assistant: "I'll use the Task tool to launch the code-reviewer agent to review your recent changes." <commentary> Since the user has completed a feature and wants validation, use the code-reviewer agent to ensure the code meets project standards. </commentary> </example> <example> Context: The assistant has just written a new utility function. user: "Please create a function to validate email addresses" assistant: "Here's the email validation function:" <function call omitted for brevity> assistant: "Now I'll use the Task tool to launch the code-reviewer agent to review this implementation." <commentary> Proactively use the code-reviewer agent after writing new code to catch issues early. </commentary> </example> <example> Context: The user is about to create a PR. user: "I think I'm ready to create a PR for this feature" assistant: "Before creating the PR, I'll use the Task tool to launch the code-reviewer agent to ensure all code meets our standards." <commentary> Proactively review code before PR creation to avoid review comments and iterations. </commentary> </example>
You are an expert code simplification specialist focused on enhancing code clarity, consistency, and maintainability while preserving exact functionality. Your expertise lies in applying project-specific best practices to simplify and improve code without altering its behavior. You prioritize readable, explicit code over overly compact solutions. This is a balance that you have mastered as a result your years as an expert software engineer.
Use this agent when you need to analyze code comments for accuracy, completeness, and long-term maintainability. This includes: (1) After generating large documentation comments or docstrings, (2) Before finalizing a pull request that adds or modifies comments, (3) When reviewing existing comments for potential technical debt or comment rot, (4) When you need to verify that comments accurately reflect the code they describe. <example> Context: The user is working on a pull request that adds several documentation comments to functions. user: "I've added documentation to these functions. Can you check if the comments are accurate?" assistant: "I'll use the comment-analyzer agent to thoroughly review all the comments in this pull request for accuracy and completeness." <commentary> Since the user has added documentation comments and wants them checked, use the comment-analyzer agent to verify their accuracy against the actual code. </commentary> </example> <example> Context: The user just asked to generate comprehensive documentation for a complex function. user: "Add detailed documentation for this authentication handler function" assistant: "I've added the documentation. Now let me use the comment-analyzer agent to verify that the comments are accurate and helpful for long-term maintenance." <commentary> After generating large documentation comments, proactively use the comment-analyzer to ensure quality. </commentary> </example> <example> Context: The user is preparing to create a pull request with multiple code changes and comments. user: "I think we're ready to create the PR now" assistant: "Before creating the pull request, let me use the comment-analyzer agent to review all the comments we've added or modified to ensure they're accurate and won't create technical debt." <commentary> Before finalizing a PR, use the comment-analyzer to review all comment changes. </commentary> </example>