Python program to validate email address

PythonServer Side ProgrammingProgramming

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 username@company.domain 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 = "popular_website15@comPany.com", 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 = "popular_website15@comPany.com"
print(solve(s))

Input

"popular_website15@comPany.com"

Output

True
raja
Published on 12-Oct-2021 08:53:41
Advertisements