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 Python function that uses a regular expression to validate whether a string is a syntactically valid email address:
```python
import re
def is_valid_email(email):
"""
Validates whether a string is a syntactically valid email address.
Args:
email (str): The email address to validate.
Returns:
bool: True if the email is valid, False otherwise.
"""
# Regular expression pattern for validating an email address
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
# Check if the email matches the pattern
if re.fullmatch(pattern, email):
return True
else:
return False
# Example usage:
print(is_valid_email("test@example.com")) # True
print(is_valid_email("invalid.email@")) # False
```
### Explanation:
1. **Regular Expression Breakdown**:
- `^[a-zA-Z0-9._%+-]+`: Matches the local part of the email (before the `@`). It allows letters, numbers, and certain special characters (`.`, `_`, `%`, `+`, `-`).
- `@`: Matches the `@` symbol.
- `[a-zA-Z0-9.-]+`: Matches the domain name (after the `@`). It allows letters, numbers, dots (`.`), and hyphens (`-`).
- `\.[a-zA-Z]{2,}$`: Matches the top-level domain (e.g., `.com`, `.org`). It requires at least 2 letters.
2. **`re.fullmatch`**: Ensures the entire string matches the pattern, not just a part of it.
3. **Return Value**: Returns `True` if the email matches the pattern, otherwise `False`.
This function provides basic validation and may not cover all edge cases (e.g., internationalized email addresses or very rare valid formats). For production use, consider using a more comprehensive library like `email-validator`.