Questo non soddisfa tutti i requisiti degli RFC 5321 e 5322, ma funziona con le seguenti definizioni.
@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+"@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,17})$";
Di seguito è riportato il codice
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[] {
"ma@hostname.com",
"ma@hostname.comcom",
"MA@hostname.coMCom",
"m.a@hostname.co",
"m_a1a@hostname.com",
"ma-a@hostname.com",
"ma-a@hostname.com.edu",
"ma-a.aa@hostname.com.edu",
"ma.h.saraf.onemore@hostname.com.edu",
"ma12@hostname.com",
"12@hostname.com",
};
var invalidEmails = new[] {
"Abc.example.com", // No `@`
"A@b@c@example.com", // multiple `@`
"ma...ma@jjf.co", // continuous multiple dots in name
"ma@jjf.c", // only 1 char in extension
"ma@jjf..com", // continuous multiple dots in domain
"ma@@jjf.com", // continuous multiple `@`
"@majjf.com", // nothing before `@`
"ma.@jjf.com", // nothing after `.`
"ma_@jjf.com", // 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));
}