Security Patterns
Regex plays a crucial role in security—from input validation to detecting malicious patterns. These patterns help protect your applications from common attacks.
Input Validation
Alphanumeric Only
Prevent special characters in usernames:
^[a-zA-Z0-9_]+$Safe Filename
Allow only safe characters in filenames:
^[\w.-]+$Rejects:
../../../etc/passwd(path traversal)file;rm -rf /(command injection)<script>(XSS in filename)
Slug/URL-Safe String
^[a-z0-9]+(?:-[a-z0-9]+)*$Matches:
my-blog-postarticle-123
Rejects:
My Blog Post(spaces, capitals)--double-dash(consecutive dashes)
SQL Injection Detection
Important: Regex-based detection is a defense-in-depth measure, not a replacement for parameterized queries. Always use prepared statements!
Common SQL Injection Patterns
(?:')|(?:--)|(?:;)|(?:\/\*)|(?:\*\/)|(?:xp_)|(?:UNION\s+SELECT)|(?:SELECT\s+.*\s+FROM)|(?:INSERT\s+INTO)|(?:DELETE\s+FROM)|(?:DROP\s+TABLE)|(?:UPDATE\s+.*\s+SET)Detect Comment Injection
(?:--|#|\/\*|\*\/)Detect String Termination
(?:'(?:[^']*')*)|(?:"(?:[^"]*")*)XSS (Cross-Site Scripting) Detection
Script Tag Detection
<script[^>]*>[\s\S]*?<\/script>Event Handler Detection
\bon\w+\s*=Detects:
onclick=onerror=onload=onmouseover=
JavaScript Protocol Detection
javascript\s*:Comprehensive XSS Pattern
(?:<script|javascript:|on\w+\s*=|<\s*img[^>]+onerror|<\s*svg[^>]+onload|expression\s*\(|vbscript:|data:text\/html)Path Traversal Detection
Directory Traversal
(?:\.\.\/|\.\.\\|%2e%2e%2f|%2e%2e\/|\.\.%2f|%2e%2e%5c)Null Byte Injection
%00|\\x00|\\0Command Injection Detection
Shell Metacharacters
[;&|`$(){}[\]<>]Common Command Patterns
(?:;|\||`|\$\(|&&|\|\|)\s*(?:cat|ls|rm|wget|curl|nc|bash|sh|python|perl|ruby|php)Password Strength Validation
Minimum Requirements
At least 8 characters, one uppercase, one lowercase, one digit:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$Strong Password
At least 12 characters, uppercase, lowercase, digit, and special character:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$API Key Detection
Generic API Key Pattern
(?:api[_-]?key|apikey|api[_-]?secret|api[_-]?token)\s*[:=]\s*['"]?([a-zA-Z0-9_-]{20,})['"]?AWS Access Key
(?:AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16}GitHub Token
gh[pousr]_[A-Za-z0-9_]{36,}JWT Token
eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*Security Best Practices
Defense in Depth: Regex validation should be one layer of your security strategy, not the only one.
1. Whitelist Over Blacklist
Bad (blacklist):
^(?!.*<script).*$Good (whitelist):
^[a-zA-Z0-9\s.,!?]+$2. Anchor Your Patterns
Always use ^ and $ for validation:
^[a-z]+$ // Validates entire string
[a-z]+ // Matches anywhere in string3. Limit Input Length
Before regex validation, check string length to prevent ReDoS:
if (input.length > 1000) {
throw new Error('Input too long');
}
if (!/^[a-z]+$/.test(input)) {
throw new Error('Invalid input');
}4. Use Non-Capturing Groups
When you don't need captures, use (?:...) for better performance:
(?:https?|ftp):// // Non-capturing
(https?|ftp):// // Capturing (slower)Security Pattern Cheatsheet
| Threat | Detection Pattern |
|---|---|
| SQL Injection | (?:')|(?:--)|(?:;)|(?:UNION\s+SELECT) |
| XSS | <script|javascript:|on\w+= |
| Path Traversal | \.\./|\.\.\\ |
| Command Injection | [;&|$(){}] |
| SSRF | (?:localhost|127\.0\.0\.1|0\.0\.0\.0) |