Python program to validate email id
Here is a Python program that validates an email ID using a regular expression:
import re
def validate_email(email):
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
if re.match(pattern, email):
return True
return False
# Test the function
email = input("Enter an email ID: ")
if validate_email(email):
print("Valid email ID")
else:
print("Invalid email ID")
Here's an explanation of the regular expression used:
^
matches the start of the string[a-zA-Z0-9._%+-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers, dot (.), hyphen (-), underscore (_), percent (%), plus sign (+)@
matches the @ symbol[a-zA-Z0-9.-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers, dot (.), hyphen (-)\.
matches a period (.) character[a-zA-Z]{2,}
matches the domain extension (it must be at least 2 characters long)$
matches the end of the string
You can modify this regular expression to fit your specific requirements.
Alternatively, you can use the email
module in Python, which provides a more comprehensive way of validating email addresses:
import email.utils
def validate_email(email):
try:
email.utils.parseaddr(email)
return True
except email.utils.ParseError:
return False
# Test the function
email = input("Enter an email ID: ")
if validate_email(email):
print("Valid email ID")
else:
print("Invalid email ID")
This function uses the email.utils.parseaddr
function to parse the email address and check if it is valid. If the parsing fails, it returns False
.