Editor

Python Program to Validate an Email Address

Intermediate · Strings

This program checks whether an email address has the right shape: a name, an @ sign, a domain and an ending like .com or .in. A pattern can only check the shape; the only way to know an address really exists and belongs to someone is to send it a confirmation email.

Program

validate_email.py
import re
# A name, then @, then one or more "word." pieces, then 2 or more letters
pattern = r"[\w.+-]+@([\w-]+\.)+[A-Za-z]{2,}"
emails = [
"riya.sharma@gmail.com",
"student+python@school.edu.in",
"no-at-sign.com",
"two@@signs.com",
"user@localhost",
"name@site.c",
] # or: emails = [input("Enter an email address: ")]
for email in emails:
if re.fullmatch(pattern, email):
print(f"{email:30} looks valid")
else:
print(f"{email:30} is not valid")
Output
riya.sharma@gmail.com          looks valid
student+python@school.edu.in   looks valid
no-at-sign.com                 is not valid
two@@signs.com                 is not valid
user@localhost                 is not valid
name@site.c                    is not valid

How it works

  1. In the pattern, [\w.+-]+ is the name part: one or more letters, digits, underscores, dots, plus signs or hyphens.
  2. After the @, ([\w-]+\.)+ needs one or more pieces like gmail. or school.edu., and [A-Za-z]{2,} needs an ending of at least two letters, such as com or in.
  3. re.fullmatch() succeeds only if the whole address fits the pattern, not just part of it.
  4. The pattern is deliberately simple: it rejects obvious mistakes but still accepts a few odd addresses, such as one with two dots in a row.
  5. No pattern can tell whether an address exists, so real websites send a confirmation email with a link or a code, and that is the only true check.

Other ways to write it

Without regular expressions

Without regular expressions
def looks_like_email(email):
if email.count("@") != 1 or " " in email:
return False
name, domain = email.split("@")
if name == "" or "." not in domain:
return False
if domain.startswith(".") or domain.endswith("."):
return False
return True
for email in ["asha@yahoo.in", "asha@", "asha yadav@mail.com", "asha@mail."]:
print(email, "->", "looks valid" if looks_like_email(email) else "not valid")
Output
asha@yahoo.in -> looks valid
asha@ -> not valid
asha yadav@mail.com -> not valid
asha@mail. -> not valid

Each if checks one rule with plain string methods: exactly one @, no spaces, a name before the @, and a dot inside the domain but not at either end.

Finding email addresses in text

Finding email addresses in text
import re
text = "Write to office@school.edu.in or to riya.s@gmail.com for details."
found = re.findall(r"[\w.+-]+@(?:[\w-]+\.)+[A-Za-z]{2,}", text)
print("Email addresses found:", found)
Output
Email addresses found: ['office@school.edu.in', 'riya.s@gmail.com']

re.findall() returns every match in the text. The group is written (?:...), which groups without capturing, because with a normal group findall() would return only the group instead of the whole address.

Try it yourself

Add "riya..sharma@gmail.com" to the list, see that the simple pattern accepts it, and think about how you would reject two dots in a row.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises