Validate Email Using Regex in Python

A toy regex. It accepts test@example.com. It also accepts garbage that looks vaguely like an email.

IntermediateString ProgramsExample 22 of 25
validate-email-using-regex.py
Run in browser
1# Program to validate email using regex
2
3import re
4
5email = input("Enter email: ")
6
7pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"
8
9if re.match(pattern, email):
10 print("Valid email")
11else:
12 print("Invalid email")

Output

Enter email: test@example.com
Valid email

What's going on

re.match from the start of the string. Pattern is roughly: stuff @ stuff . stuff.

Real email validation is a tar pit. This one fails a@b (no dot in the domain) and lets through a@b.c which is not a mailbox. Fine for a class exercise. Do not ship it.