Validating E-mail Addresses With Regex (PCRE)

By | Regex

I was given the challenge of validating e-mails with pure regex. This is what I came up with. I included all the valid e-mails that get selected with the regex below. I am using the inline mode modifier (?x) to make it easier to read.

NOTE1: I am heavily using look aheads (positive & negative).

NOTE2: This is valid under PCRE.

(?x)^
# Positive Look Aheads
(?=.*\.[A-Z]+$)              # Requires ending with alpha characters
(?=([[:alnum:]\.+-]+)@(?1))  # specifying allowed characters
# Negative Look Aheads
(?!.*@.*@)                   # No multiple @ signs
(?!.*?@.*\.\d+$)             # No ending in digits
(?!([[:punct:]]))            # No starting with punctuation
(?!.*\.{2,})                 # No double periods
(?!.*(?2)@)                  # No punct to left of @        
(?!.*@(?2))                  # No punct to right of @
.*

SAMPLE DATA: VALID E-MAILS

email@example.web
email@example.com
firstname.lastname@example-ya.com
email@subdomain.example.com
firstname+lastname@example.com
email@123.123.123.com
1234567890@example.com
email@example-one.com
email@example.name
email@example.museum
email@example.co.jp
firstname-lastname@example.com
amazing@website.amazing

SAMPLE DATA: INVALID E-MAILS

plainaddress
#@%^%#$@#$@#.com
@example.com
Joe Smith <email@example.com>
email.example.com
email@example@example.com
.email@example.com
email.@example.com
email..email@example.com
あいうえお@example.com
email@example.com (Joe Smith)
email@example
email@-example.com
email@111.222.333.44444
email@example..com
Abc..123@example.com

One Response to " Validating E-mail Addresses With Regex (PCRE) "

  1. […] Validating E-mail Addresses With Regex (PCRE) 🔊 Zeratul Impression from Starcraft (1998 Version) You need to own your entertainment […]

Leave a Reply

Your email address will not be published. Required fields are marked *