Best Regular Expression for Email Validation in C#

Sachin Kainth picture Sachin Kainth · Apr 23, 2013 · Viewed 264.7k times · Source

I have seen a multitude of regular expressions for different programming languages that all purport to validate email addresses. I have seen many comments saying that the expressions in question do not work for certain cases and that they are either too strict or too permissive. What I'm looking for is a regular expression that I can use in my C# code that is definitive.

The best thing I have found is this

^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$

Is there something better?

Answer

Parimal Raj picture Parimal Raj · Apr 23, 2013

Email address: RFC 2822 Format
Matches a normal email address. Does not check the top-level domain.
Requires the "case insensitive" option to be ON.

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

Usage :

bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);