How to re.search module on python

Tags: , ,



In a part of my program, I have to check an email entered and I want to make it so any domain name can work for the checker, current code as below;

import re #needed to check email
emailFormat = '^[a-z0-9]+[._]?[a-z0-9]+[@]w+[.]w+$' #general form of email

def check(email):  #Validation for email
    if(re.search(emailFormat,email)): #pass expression and string in  search() 
        return "Valid Email"
    else:  
        return "Invalid Email"

enterEmail=str(input('enter email'))

print(check(enterEmail))

Currently, this will work for any email in for example@email.com but as some emails are in the form example@email.co.uk so how can I can make ’emailFormat’ valid for any domain form. Also, the check will work for company/school emails, for example, example@school.com or example@email.school just anything which doesn’t contain a ‘two-part’ domain name like ‘co.uk’ so will I need another variable to check for that or is it possible to do in one command.

Thanks in advance for anything useful.

Answer

This will work on the two letters domains as well, and on email.school as well.

import re #needed to check email
emailFormat = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$)"

def check(email):  #Validation for email
    if(re.search(emailFormat,email)): #pass expression and string in  search()
        return "Valid Email"
    else:
        return "Invalid Email"

enterEmail=str(input('enter email'))

print(check(enterEmail))

Further reading on the above :- https://emailregex.com/



Source: stackoverflow