Python using regular expressions for email validation
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
(
)
:
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
,
)
:
return
True
else
:
return
False
Test email
=
"example@example.com"
if
validate_email
(
)
:
(
f
"{email} is a valid email address"
)
else
:
(
f
"{email} is not a valid email address"
)
Code analysis:
import re: import Python's regular expression module.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:
^[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.re.match(pattern, email): When usingre.matchmethod checks whether the email string matches the regular expression pattern.if validate_email(email):: Callingvalidate_emailfunction validates the email address and outputs corresponding information based on the result.
Output result:
example@example.com 是一个有效的邮箱地址
Python3 Examples