Over the years I have slowly developed a regular expression that validates MOST email addresses correctly, assuming they don't use an IP address as the server part.
I use it in several PHP programs, and it works most of the time. However, from time to time I get contacted by someone that is having trouble with a site that uses it, and I end up having to make some adjustment (most recently I realized that I wasn't allowing 4-character TLDs).
What is the best regular expression you have or have seen for validating emails?
I've seen several solutions that use functions that use several shorter expressions, but I'd rather have one long complex expression in a simple function instead of several short expression in a more complex function.
I use
Which is the one used in ASP.NET by the RegularExpressionValidator.
Don't know about best, but this one is at least correct, as long as the addresses have their comments stripped and replaced with whitespace.
Seriously. You should use an already written library for validating emails. The best way is probably to just send a verification e-mail to that address.
It’s easy in Perl 5.10 or newer:
You could use the one employed by the jQuery Validation plugin:
While deciding which characters are allowed, please remember your apostrophed and hyphenated friends. I have no control over the fact that my company generates my email address using my name from the HR system. That includes the apostrophe in my last name. I can't tell you how many times I have been blocked from interacting with a website by the fact that my email address is "invalid".
This regex is from Perl's Email::Valid library. I believe it to be the most accurate, it matches all 822. And, it is based on the regular expression in the O'Reilly book: