Skip to content

Instantly share code, notes, and snippets.

@rishisidhu
Created June 25, 2020 16:57
Show Gist options
  • Save rishisidhu/f302d3ddb5f4317513fa623d4d92a711 to your computer and use it in GitHub Desktop.
Save rishisidhu/f302d3ddb5f4317513fa623d4d92a711 to your computer and use it in GitHub Desktop.
A python code that describes how regex can be used to validate an email ID
import re
test_email_1 = "Jane.doe1971@gmail.com"
test_email_2 = "JD@msn.org.edu"
test_email_3 = "J.A.N.E@web123.AI"
test_emails = [test_email_1, test_email_2, test_email_3]
def extract_info(email_string):
# Search for username
# Methodology
# All alphabets and numbers before @
# () anything between parenthesis is matched and returned
# [] contains the set of characters
# that may occur in the matched string
u = re.search('([A-Za-z0-9\.]*)@', email_string)
username = u.group(1)
# Search for domain name
# All alphabets and numbers between @ and dot
# Escape the dot using backslash
d = re.search('@([A-Za-z0-9]*)\.', email_string)
domain = d.group(1)
# Search for TLD
# Anything after the first dot
# that occurs after the @ sign
t = re.search('@[A-Za-z0-9]*\.([A-Za-z\.]*)', email_string)
TLD = t.group(1)
print("\n*****************************\nEMAIL: ", email_string)
print("Username: ", username)
print("Domain: ", domain)
print("TLD: ", TLD, "\n")
for email in test_emails:
extract_info(email)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment