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
To solve this problem, we need to write a Python function that validates whether a given string is a syntactically valid email address using a regular expression. The function should return `True` if the email is valid and `False` otherwise.
### Approach
The approach involves using a regular expression (regex) to match the structure of a valid email address. The regex is designed to cover the basic syntactic rules for email addresses, ensuring that the local part and domain part conform to specific patterns.
1. **Local Part**: The local part of the email address (the part before the `@` symbol) must:
- Start and end with an alphanumeric character.
- Can include letters, digits, dots, hyphens, underscores, percent signs, and plus signs.
- Can have multiple segments separated by dots, but each segment must start and end with an alphanumeric character.
2. **Domain Part**: The domain part of the email address (the part after the `@` symbol) must:
- Contain at least one dot.
- Each segment (before the dot) can include letters, digits, hyphens, and dots.
- The top-level domain (TLD, the part after the last dot) must be between 2 and 6 characters long.
The regex pattern is constructed to enforce these rules, ensuring that the entire string matches the pattern from start to end.
### Solution Code
```python
import re
def is_valid_email(email):
pattern = r'^[a-zA-Z0-9]([a-zA-Z0-9._%+-]*[a-zA-Z0-9])?@([a-zA-Z0-9-]+\.)+[a-zA-Z0-9-]{2,6}$'
return bool(re.match(pattern, email))
```
### Explanation
- **Regex Breakdown**:
- `^[a-zA-Z0-9]`: Ensures the local part starts with an alphanumeric character.
- `([a-zA-Z0-9._%+-]*[a-zA-Z0-9])?`: Allows for additional characters in the local part, ensuring it ends with an alphanumeric character.
- `@`: Matches the `@` symbol separating the local and domain parts.
- `([a-zA-Z0-9-]+\.)+`: Ensures the domain part has at least one dot and each segment (before the dot) contains valid characters.
- `[a-zA-Z0-9-]{2,6}$`: Ensures the top-level domain (TLD) is between 2 and 6 characters long.
This regex effectively checks the syntax of an email address, ensuring it meets the basic structural requirements.