Python Uses Regular Expressions for Email Validation

Document 对象参考手册Python3 Examples

In Python, we can use regular expressions to verify whether a string conforms to the email format. Email usually contains a username, the @ symbol, and a domain part. We can useremodule to implement this functionality.

Examples

import re

def validate_email(email):
    # Define the regex pattern for email
    pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$'
    # Use the re.match method for matching
    if re.match(pattern, email):
        return True
    else:
        return False

# Test email
email = "example@example.com"
if validate_email(email):
    print(f"{email} is a valid email address")
else:
    print(f"{email} is not a valid email address")

Code explanation:

  1. import re: Import Python's regular expression module.
  2. pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$': Defined a regular expression pattern for matching email addresses. This pattern includes:
    • ^[a-zA-Z0-9_.+-]+: Matches the username part, which can contain letters, digits, underscores, dots, plus signs, and hyphens.
    • @: Matches the @ symbol in the email address.
    • [a-zA-Z0-9-]+: Matches the domain part, which can contain letters, digits, and hyphens.
    • .[a-zA-Z0-9-.]+$: Matches the top-level domain part, which can contain letters, digits, dots, and hyphens.
  3. re.match(pattern, email): Usere.matchmethod to check whether the email string matches the regex pattern.
  4. if validate_email(email):: Callvalidate_emailfunction to validate the email address, and output corresponding information based on the returned result.

Output result:

example@example.com 是一个有效的邮箱地址

Document 对象参考手册Python3 Examples

Other Extensions