Search code snippets, questions, articles...

Python code to validate email address using regex

To validate email addresses using python, regex can be quite helpful. You can import the python regex module - re and use it to validate the email address.
import re

def validate_email(email):
  email_pattern = r'\b[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
  if ( re.fullmatch(email_pattern, email) ):
    print("Email is Valid")
  else:
    print("Email is Invalid")

validate_email("[email protected]")
# -> prints - Email is Valid

validate_email("testdomain.com")
# -> prints - Email is Invalid
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

In the code snippet, we are importing the python regex module using the below code.

import re

The regex pattern that we are using to validate the email address is as below:

email_pattern = r'\b[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'

Finally, the syntax that can be used to check regular expressions against the email address text is as below.

re.fullmatch(email_pattern, email)

Search Index Data (The code snippet can also be found with below search text)

regex expression to check if email is valid or not
Was this helpful?
0 Comments