Skip to content

Instantly share code, notes, and snippets.

@LordGhostX
Last active August 13, 2023 17:09
Show Gist options
  • Save LordGhostX/7999cee1064efab7fdf5c290b0bc35b6 to your computer and use it in GitHub Desktop.
Save LordGhostX/7999cee1064efab7fdf5c290b0bc35b6 to your computer and use it in GitHub Desktop.
RegEX to validate email
# validate email addresses
def validate_email(email):
pattern = r"(^(?!-|\.)([a-zA-Z0-9._%+-]+)@(?!-)[a-zA-Z0-9.-]+(?<=[a-zA-Z0-9])\.[a-zA-Z]{2,}$)"
if re.match(pattern, email):
return True
else:
return False
if __name__ == "__main__":
# test email validation
test_cases = [
("email@example.com", True),
("email123@example.com", True),
("my-email@example.com", True),
("my.email@example.com", True),
("my_email@example.com", True),
("email@123.com", True),
("email@example.co.uk", True),
("email@sub.example.com", True),
("email+me@example.com", True),
("a@b.com", True),
("email.example.com", False),
("email@", False),
("@example.com", False),
("my email@example.com", False),
("email@exa#mple.com", False),
("email@ex@ample.com", False),
("email@-example.com", False),
("email@example-.com", False),
("email@example", False),
("email@example.c", False),
(".me@mail.com", False),
("-me@mail.com", False)
]
for case in test_cases:
assert validate_email(case[0]) is case[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment