Most Recent Update: 2013-03-26: If you found this page by searching, the HTML5 email address regexp you are looking for is:
/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?)*$/
(This should be all one line.) This regexp works unchanged in either Perl or JavaScript.
Version history: this version improves upon the previous, shorter version which was here from Feb 2012 to March 2013 in that it restricts domain labels to 255 characters and prevents them beginning or ending with a “-“. That prior version differed from the version originally calculated in May 2011 in the blog post below, in that it stopped using \w and started using non-capturing parentheses.
Original post follows:
Summary: can anyone help me out by confirming I’ve correctly calculated the regexp to match the HTML5 email address format spec?
The regexp to match official RFC2822 email addresses is:
(?:[a-z0-9!#$%&’*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&’*+/=?^_`{|}~-]+)*|”(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*”)@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
HTML5 realises this is ridiculous, and proposed a more limited format for email addresses. Having read the spec, and followed the logic below, I think the regexp form of the spec is this:
/^[\w.!#$%&’*+\-/=?\^`{|}~]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/i
Am I right?
Logic:
HTML5 says:
“1*( atext / “.” ) “@” ldh-str *( “.” ldh-str ) where atext is defined in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section 3.5.”
Mining those RFCs:
atext = ALPHA / DIGIT / ; Printable US-ASCII
"!" / "#" / ; characters not including
"$" / "%" / ; specials. Used for atoms.
"&" / "'" /
"*" / "+" /
"-" / "/" /
"=" / "?" /
"^" / "_" /
"`" / "{" /
"|" / "}" /
"~"
<ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
<let-dig-hyp> ::= <let-dig> | "-"
<let-dig> ::= <letter> | <digit>
<letter> ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case
<digit> ::= any one of the ten digits 0 through 9
That leads to the following, if I’m not mistaken:
/^[a-zA-Z0-9.!#$%&’*+\-/=?\^_`{|}~]+@[a-z0-9-]+(\.[a-zA-Z0-9-]+)*$/i
which can be reduced, by using ‘\w’, to:
/^[\w.!#$%&’*+\-/=?\^`{|}~]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*$/i