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
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
- In the pattern,
[\w.+-]+is the name part: one or more letters, digits, underscores, dots, plus signs or hyphens. - After the
@,([\w-]+\.)+needs one or more pieces likegmail.orschool.edu., and[A-Za-z]{2,}needs an ending of at least two letters, such ascomorin. re.fullmatch()succeeds only if the whole address fits the pattern, not just part of it.- 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.
- 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
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
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.
Related programs
- Check if a String Contains a Substring
- Store and Search User IDs and Passwords in a CSV File
- Generate a Random Password
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Count the Frequency of Each Character in a String
- Count the Words in a String
- Remove Punctuation from a String
All Python programs · CBSE class 12 practical file · Python exercises