This does not meet all of the requirements of RFCs 5321 and 5322, but it works with the following definitions.
@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
Below is the code
const String pattern =
@"^([0-9a-zA-Z]" + //Start with a digit or alphabetical
@"([\+\-_\.][0-9a-zA-Z]+)*" + // No continuous or ending +-_. chars in email
@")+" +
@"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
var validEmails = new[] {
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
};
var invalidEmails = new[] {
"Abc.example.com", // No `@`
"A@b@[email protected]", // multiple `@`
"[email protected]", // continuous multiple dots in name
"[email protected]", // only 1 char in extension
"[email protected]", // continuous multiple dots in domain
"ma@@jjf.com", // continuous multiple `@`
"@majjf.com", // nothing before `@`
"[email protected]", // nothing after `.`
"[email protected]", // nothing after `_`
"ma_@jjf", // no domain extension
"ma_@jjf.", // nothing after `_` and .
"ma@jjf.", // nothing after `.`
};
foreach (var str in validEmails)
{
Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
}
foreach (var str in invalidEmails)
{
Console.WriteLine("{0} - {1} ", str, Regex.IsMatch(str, pattern));
}