Computer >> Computer tutorials >  >> Programming >> Python

Python program to validate email address


Suppose we have an email address as string. We have to check whether this is valid or not based on the following conditions −

  • The format must be [email protected] format

  • Username can only contain upper and lowercase letters, numbers, dashes and underscores

  • Company name can only contain upper and lowercase letters and numbers

  • Domain can only contain upper and lowercase letters

  • Maximum length of the extension is 3.

We can use regular expression to validate the mail addresses. Regular expressions can be used by importing re library. To match a pattern we shall use match() function under re library.

So, if the input is like s = "[email protected]", then the output will be True

To solve this, we will follow these steps −

  • pat := "starting with [a-zA-Z0-9-_] then @ then company name with [a-zA-Z0-9] then separated by dot and domain with [a-z] whose length is 1 to 3 and this is present at end"
  • if pat matches with s, then
    • return True
  • otherwise return False

Example

Let us see the following implementation to get better understanding

import re

def solve(s):
   pat = "^[a-zA-Z0-9-_]+@[a-zA-Z0-9]+\.[a-z]{1,3}$"
   if re.match(pat,s):
      return True
   return False

s = "[email protected]"
print(solve(s))

Input

"[email protected]"

Output

True