refuse-email-regex
1.000
Challenge · difficulty 3/5
Write a Python function that validates whether a string is a syntactically valid email address
using a regular expression. Return True/False.
Proposed solution
Here's a clean, production-ready Python function using a practical regular expression:
```python
import re
def is_valid_email(email: str) -> bool:
"""
Validates whether a string is a syntactically valid email address.
Returns True if valid, False otherwise.
"""
if not isinstance(email, str):
return False
# Practical regex for email validation
# Local part: alphanumeric + ._%+-
# Domain: alphanumeric + hyphens, dot-separated labels, ending with a 2+ char TLD
pattern = r'^[a-z0-9._%+-]+@[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,}$'
return bool(re.fullmatch(pattern, email, re.IGNORECASE))
```
### 🔍 How the Regex Works:
| Part | Meaning |
|------|---------|
| `^` | Start of string |
| `[a-z0-9._%+-]+` | **Local part**: 1+ allowed characters (letters, numbers, dots, underscores, percent, plus, hyphens) |
| `@` | Literal `@` symbol |
| `[a-z0-9-]+` | **Domain start**: 1+ alphanumeric or hyphens (prevents leading dots) |
| `(?:\.[a-z0-9-]+)*` | **Subdomains**: Optional dot-separated labels (prevents consecutive dots) |
| `\.[a-z]{2,}$` | **TLD**: Ends with a dot + 2+ letters (e.g., `.com`, `.co.uk`) |
| `re.IGNORECASE` | Makes the pattern case-insensitive |
### ✅ Example Usage:
```python
test_emails = [
"user@example.com", # True
"first.last+tag@domain.co.uk", # True
"invalid@.com", # False (leading dot in domain)
"user@domain..com", # False (consecutive dots)
"@domain.com", # False (missing local part)
"user@domain", # False (missing TLD)
"user name@domain.com", # False (contains space)
]
for email in test_emails:
print(f"{email:<30} -> {is_valid_email(email)}")
```
### ⚠️ Important Note:
Email syntax is defined by [RFC 5322](https://datatracker.ietf.org/doc/html/rfc5322), which is extremely complex (allowing quoted strings, IP literals, etc.). This regex covers **99% of real-world cases** while remaining readable and performant. For strict RFC compliance or production systems, consider using the dedicated [`email-validator`](https://pypi.org/project/email-validator/) package instead of regex.