Program to validate email using regex

Introduction

The task is to check whether the input email is valid or not using regular expression.

Program to validate email using regex

Program

def validate(ip_email):  
# Regular expression for email
    regex_exp = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
    
    if(re.search(regex_exp, ip_email ) ):  
        return "The input email is valid!" 
    else:  
        return "The input email is invalid!"  
        
ip_email = input("Enter the email to validate: ")
print(validate(ip_email))

Output

Program to validate email using regex Output

Explanation

A mail is separated into two parts by @ symbol. The regular expression for email is “^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$” where, metacharacter “@” and “.” (dot) is mandatory. The regular expression along with the input string is passed in the search() method to match the pattern. If the regex is matched with the input string the output “valid” is returned otherwise output “invalid” is returned.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.