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?
This question is related to
c#
regex
email-validation
Email Validation Regex
^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+.)+[a-z]{2,5}$
Or
^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+[.])+[a-z]{2,5}$
Demo Link:
I would like to suggest new EmailAddressAttribute().IsValid(emailTxt)
for additional validation before/after validating using RegEx
Remember EmailAddressAttribute
is part of System.ComponentModel.DataAnnotations namespace
.
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
Updated answer for 2019.
Regex object is thread-safe for Matching functions. Knowing that and there are some performance options or cultural / language issues, I propose this simple solution.
public static Regex _regex = new Regex(
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Singleline);
public static bool IsValidEmailFormat(string emailInput)
{
return _regex.IsMatch(emailInput);
}
Alternative Configuration for Regex:
public static Regex _regex = new Regex(
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Compiled);
I find that compiled is only faster on big string matches, like book parsing for example. Simple email matching is faster just letting Regex interpret.
This C# function uses a regular expression to evaluate whether the passed email address is syntactically valid or not.
public static bool isValidEmail(string inputEmail)
{
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}
Source: Stackoverflow.com