Practical Regex Patterns
Common Use Cases
Email Validation
import re
def validate_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
## Email validation examples
emails = [
'[email protected]',
'invalid.email',
'[email protected]'
]
for email in emails:
print(f"{email}: {validate_email(email)}")
Password Strength Checking
graph TD
A[Password Regex] --> B{Criteria}
B --> |Length| C[Minimum 8 characters]
B --> |Uppercase| D[At least one capital letter]
B --> |Lowercase| E[At least one lowercase letter]
B --> |Number| F[At least one digit]
B --> |Special Char| G[At least one special character]
Password Validation Pattern
def check_password_strength(password):
patterns = [
r'.{8,}', ## Minimum length
r'[A-Z]', ## Uppercase letter
r'[a-z]', ## Lowercase letter
r'\d', ## Digit
r'[!@#$%^&*()]' ## Special character
]
return all(re.search(pattern, password) for pattern in patterns)
## Test passwords
passwords = [
'weak',
'StrongPass123!',
'NoSpecialChar123'
]
for pwd in passwords:
print(f"{pwd}: {check_password_strength(pwd)}")
Log File Parsing
Log Pattern |
Description |
Use Case |
\d{4}-\d{2}-\d{2} |
Date extraction |
Filtering logs by date |
ERROR:\s.* |
Error log matching |
Identifying error messages |
\b\w+\[(\d+)\] |
Process ID extraction |
Tracking specific processes |
Log Parsing Example
log_entries = [
'2023-06-15 ERROR: Database connection failed',
'2023-06-15 INFO: Server started [1234]',
'WARNING: Memory usage high'
]
## Extract dates and error messages
for entry in log_entries:
date_match = re.search(r'\d{4}-\d{2}-\d{2}', entry)
error_match = re.search(r'ERROR:\s.*', entry)
if date_match:
print(f"Date: {date_match.group()}")
if error_match:
print(f"Error: {error_match.group()}")
Web Scraping Patterns
text = "Check out https://www.example.com and http://labex.io"
urls = re.findall(r'https?://[^\s]+', text)
print("Extracted URLs:", urls)
- Compile regex patterns for repeated use
- Use specific patterns to improve matching speed
- Avoid overly complex regex expressions
LabEx recommends practicing these practical regex patterns to enhance your text processing skills.