15 Most Useful Regex Patterns Every Developer Should Know
Certain regex patterns come up again and again in everyday development. This article compiles 15 of the most practical patterns covering form validation, data extraction, and text processing.
Form Validation Patterns
1. Email Address
Pattern: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
This pattern balances accuracy and practicality. A fully RFC 5322-compliant regex is too complex for real-world use.
2. URL Validation
Pattern: ^https?:\/\/[\w.-]+(?:\.[\w.-]+)+[\w.,@?^=%&:/~+#-]*$
3. Password Strength
At least 8 chars with upper, lower, and digit: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$
4. Phone Number (US)
Pattern: ^\+?1?[-. ]?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}$
Data Extraction Patterns
5. IPv4 Address
Pattern: ^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.?){4}$
6. HTML Tag Extraction
Pattern: <([a-z]+)[^>]*>(.*?)<\/\1>
7. Date Format (YYYY-MM-DD)
Pattern: ^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$
8. Hex Color Code
Pattern: ^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$
Text Processing Patterns
9. Remove Extra Whitespace
Pattern: \s+ (replace with single space)
10. Extract Parenthetical Content
Pattern: \(([^)]+)\)
11. File Extension
Pattern: \.([a-zA-Z0-9]+)$
12. Strip HTML Tags
Pattern: <[^>]*> (replace with empty string)
Important: Regex is suitable for basic format validation but should not be the sole security measure. For email, URL, and similar data, combine with backend validation and dedicated libraries.
Test Your Patterns Online
Try the Regex Tester Tool →References
- OWASP Foundation. "Input Validation Cheat Sheet." OWASP Cheat Sheet Series. https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html
- Resnick, P. "Internet Message Format." IETF RFC 5322, 2008. https://datatracker.ietf.org/doc/html/rfc5322
- Berners-Lee, T. et al. "Uniform Resource Identifier (URI): Generic Syntax." IETF RFC 3986, 2005. https://datatracker.ietf.org/doc/html/rfc3986