Common Regex Patterns
Regular expressions are powerful, but they can be complex to write. Here's a collection of commonly used patterns that you can use as building blocks for your own expressions.
Email Validation
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
This pattern matches most common email addresses:
- Username can contain letters, numbers, and certain special characters
- Domain name follows standard rules
- TLD must be at least 2 characters
URL Matching
^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$
This pattern matches web URLs:
- Optional http:// or https:// prefix
- Domain name with optional subdomains
- TLD between 2-6 characters
- Optional path components
Phone Numbers
^\+?(\d{1,3})?[-. ]?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4}$
This pattern matches various phone number formats:
- Optional country code with '+'
- Area code with or without parentheses
- Separators can be spaces, dots, or hyphens
Date Formats
^(0?[1-9]|1[0-2])[\/\-](0?[1-9]|[12]\d|3[01])[\/\-](19|20)\d{2}$
This pattern matches dates in MM/DD/YYYY format:
- Months: 01-12 or 1-12
- Days: 01-31 or 1-31
- Years: 1900-2099
- Separators can be / or -
Tips for Using These Patterns
- Validation vs. Sanitization: Remember that regex validation should be part of a larger validation strategy
- Performance: Complex patterns can be computationally expensive
- Maintenance: Break down complex patterns into smaller, documented pieces
- Testing: Always test patterns with both valid and invalid inputs