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?
Regex : ^(.+)@(.+)$ This one is simplest and only cares about '@' symbol. Before and after '@' symbol, there can be any number of characters.
[a-zA-Z0-9+_. -] matches one character from the English alphabet (both cases), digits, “+”, “_”, “.” and, “-” before the @ symbol. + indicates the repetition of the above-mentioned set of characters one or more times. @ matches itself.
Don't use regexes for validating emails, unless you have a good reason not to. Use a verification mail instead. In most cases, a regex that simply checks that the string contains an @ is enough.
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);
First option (bad because of throw-catch, but MS will do work for you):
bool IsValidEmail(string email) { try { var mail = new System.Net.Mail.MailAddress(email); return true; } catch { return false; } }
Second option is read I Knew How To Validate An Email Address Until I Read The RFC and RFC specification
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With