Validate email format with regex in Python
A Python function using a regex pattern to validate simple email formats, returning True or False for each input.
Python code
18 linesimport re
def is_valid_email(email):
pattern = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'
return bool(re.match(pattern, email))
if __name__ == "__main__":
test_emails = [
"user@example.com",
"first.last@sub.domain.org",
"invalid-email",
"user@.com",
"user@domain",
"user.name+tag@gmail.com",
"user@domain.c"
]
for email in test_emails:
print(f"{email}: {is_valid_email(email)}")
Output
user@example.com: True
first.last@sub.domain.org: True
invalid-email: False
user@.com: False
user@domain: False
user.name+tag@gmail.com: True
user@domain.c: False
How it works
The function defines a regular expression that captures the commonly accepted structure of an email: local part, @ symbol, domain name, and top-level domain. re.match anchors the pattern at the start of the string, and the ^ and $ ensure the entire string is validated. The pattern allows typical characters in the local part and requires at least two letters in the top-level domain. This is a simple validation suitable for basic checks, not a full RFC-compliant email parser.
Common mistakes
- Using `re.search` instead of `re.match` may allow partial matches if the pattern doesn't fully anchor.
- Forgetting to escape special characters in the regex pattern, like the dot in the domain.
- Assuming regex validates real email existence; it only checks format.
- Missing the `$` anchor could let invalid strings with extra characters pass.
Variations
- Use `re.fullmatch` instead of `re.match` with `^` and `$` for the same purpose.
- Use a library like `email-validator` for more robust, standards-compliant validation.
Real-world use cases
- Validating user input in sign-up forms before creating an account.
- Filtering out malformed email addresses from a CSV or database before sending newsletters.
- Checking configuration files where email addresses are used for notifications or alerts.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.