Example output
Here's a Python code snippet that uses a regular expression to validate an email address format:
```python
import re
def is_valid_email(email):
# Define the regular expression for validating an email address
email_regex = re.compile(
r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
)
# Use the regex to check if the email matches the pattern
return bool(email_regex.match(email))
# Example usage
emails_to_test = [
"test@example.com", # Valid
"user.name+tag+sorting@example.com", # Valid
"user@sub.domain.com", # Valid
"user@domain", # Invalid, no TLD
"user@domain.c", # Invalid, TLD too short
"user@domain.toolongtld", # Valid, unusual but technically valid TLD
"@missingusername.com", # Invalid, missing username
"missingatdomain.com", # Invalid, missing '@'
"user@.domain.com", # Invalid, domain starts with a dot
"user@domain..com" # Invalid, double dot in domain
]
for email in emails_to_test:
print(f"{email}: {is_valid_email(email)}")
```
### Explanation of the Regular Expression
- `^` and `$`: These are anchors that denote the start and end of the string. This ensures the entire string is validated as an email address.
- `[a-zA-Z0-9._%+-]+`: This matches the username part of the email. It allows alphanumeric characters and some special characters (`.`, `_`, `%`, `+`, `-`). The `+` ensures that at least one character is present.
- `@`: This is the literal `@` symbol, separating the username from the domain.
- `[a-zA-Z0-9.-]+`: This matches the domain part of the email. It allows alphanumeric characters, dots (`.`), and hyphens (`-`). The `+` ensures that at least one character is present.
- `\.`: This matches the literal dot (`.`) in the domain, separating the domain name from the TLD.
- `[a-zA-Z]{2,}`: This matches the top-level domain (TLD). It ensures that the TLD is composed of at least two alphabetic characters (e.g., `.com`, `.org`).
### How the Code Works
1. **Compile the Regular Expression:** The `re.compile()` function is used to compile the regular expression pattern into a regex object for reuse.
2. **Match the Email:** The `match()` method checks if the input email matches the pattern from start to end.
3. **Return the Result:** The function returns `True` if the email is valid according to the regular expression and `False` otherwise.
### Example Output
The code tests several email addresses, printing whether each one is valid:
```plaintext
test@example.com: True
user.name+tag+sorting@example.com: True
user@sub.domain.com: True
user@domain: False
user@domain.c: False
user@domain.toolongtld: True
@missingusername.com: False
missingatdomain.com: False
user@.domain.com: False
user@domain..com: False
```
This example illustrates how different email formats are validated using the regular expression.