Created
February 13, 2023 16:14
-
-
Save deangrant/011ed5bd839727c1890b33bb964da0d0 to your computer and use it in GitHub Desktop.
Checks if a string is a valid email address in Python. Uses a regular expression to check that the email address conforms to the syntax rules specified in RFC 5322.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_valid_email( | |
email_str: str | |
) -> bool: | |
""" | |
Check if a string is a valid email address. The regular expression checks | |
that the email address conforms to the syntax rules specified in RFC 5322. | |
Parameters: | |
email_str (str): The string to check. | |
Returns: | |
bool: True if the string is a valid email address, False otherwise. | |
Example: | |
>>> is_valid_email("user@example.com") | |
True | |
>>> is_valid_email("user@example") | |
False | |
""" | |
# Use email.utils.parseaddr to split the email address into parts | |
# and get the email address part. | |
email_address = email.utils.parseaddr(email_str)[1] | |
# Use a regular expression to check that the email address is valid. | |
regex = r"(?=.{1,64}@.{1,255}$)(?=.{1,64}\.{1,255}$)[^@ ]+@[^@ ]+\.[^@ ]{2,}$" | |
return re.match(regex, email_address) is not None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment