Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python using regular expressions for email validation

Python using regular expressions for email validation

Document Object Reference Manual Python3 Examples

In Python, we can use regular expressions to verify whether a string matches the email format. An email usually contains a username, an @ symbol, and a domain part. We can use re module to achieve this.

Example

import

re

def

validate_email

(

email

)

:

   

Define the regular expression 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 analysis:

  1. import re: import Python's regular expression module.
  2. pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$': define a regular expression pattern for matching email addresses. This pattern includes:
  3. ^[a-zA-Z0-9_.+-]+: matches the username part, which can contain letters, digits, underscores, dots, plus signs, and minus signs.
  4. @: matches the @ symbol in the email.
  5. [a-zA-Z0-9-]+: matches the domain part, which can contain letters, digits, and minus signs.
  6. .[a-zA-Z0-9-.]+$: matches the top-level domain part, which can contain letters, digits, dots, and minus signs.
  7. - `^[a-zA-Z0-9_.+-]+`: matches the username part, which can contain letters, digits, underscores, dots, plus signs, and minus signs. - `@`: matches the @ symbol in the email. - `[a-zA-Z0-9-]+`: matches the domain part, which can contain letters, digits, and minus signs. - `.[a-zA-Z0-9-.]+$`: matches the top-level domain part, which can contain letters, digits, dots, and minus signs.
    1. re.match(pattern, email): When using re.match method checks whether the email string matches the regular expression pattern.
    2. if validate_email(email):: Calling validate_email function validates the email address and outputs corresponding information based on the result.

    Output result:

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

    Document Object Reference Manual Python3 Examples