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 browser1# Program to validate email using regex23import re45email = input("Enter email: ")67pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"89if 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.