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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 12 views 0 copies

Python code

18 lines
Python 3.9+
import 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

stdout
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

  1. Use `re.fullmatch` instead of `re.match` with `^` and `$` for the same purpose.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.