Validate Email Format in Python
Test an email-shaped string with Python regex and if. For new programmers, this example separates a rough formatting rule from a mailbox that actually exists.
1# Program to validate email format using regex23import re45email = input("Enter an email address: ")67pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"89if re.match(pattern, email):10 print("Valid email format")11else:12 print("Invalid email format")
Output
Valid email format
The sample fits the toy pattern; the message says nothing about whether delivery would work.
In this one
- Read start and end anchors
- Use a match result as a condition
- Separate format checks from mailbox verification
How it works
- 1
Import re and read email.
- 2
Apply the pattern with re.match.
- 3
Print the format result according to whether a match object is returned.
Edge cases
Plus tag
Enter user+tag@example.com.
This toy pattern rejects the plus even though such mailbox names can be valid.
Repeated dots
Enter a..b@example.com.
The loose character groups can accept invalid local-part shapes.
What's going on
This pattern recognizes a rough local-part@domain.suffix shape. re.match starts at the beginning, while ^ and $ mark the intended boundaries. The condition uses the match object's truth value to choose a message.
The allowed groups include word characters, dots, and hyphens. That makes the expression easy to study but much looser than actual mailbox rules in some places and too restrictive in others. For example, a plus tag is rejected while repeated dots can slip through.
user@example.com passes. a@b fails because there is no final dot group. Neither a passing shape nor a domain-looking suffix proves a mailbox exists. Real signup flows need confirmation rather than a homemade regex as proof. Python's $ can also match just before a final newline, so strict whole-input checks usually use fullmatch.
After this program
If the idea is still fuzzy, read Day 8: Conditional Statements in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 conditional programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Does a match prove the mailbox exists?
Pick an answer to check it.
Question 2
Why can a plus-tag address fail?
Pick an answer to check it.
Questions people ask
Does a match prove the mailbox exists?
No. The regex tests text shape, not delivery or ownership.
Why can a plus-tag address fail?
The local-part character class does not include +.
What is a stronger check for ownership?
Send a confirmation link or code in a real application; a regex alone cannot verify ownership.