Porównałem te dwie metody na emailach z: https://en.wikipedia.org/wiki/Email_address#Examples
using System;
using System.Net.Mail;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
const string EMAIL_REGEX = @"^[\w\.]+(@)[\w\-\.]{1,256}(\.)([\w\.]{1,256}?)([A-z0-9]{1,3})";
public static bool B(string emailAddress)
{
return Regex.IsMatch(emailAddress, EMAIL_REGEX);
}
public static bool A(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
public static void Main()
{
var validEmails = new[]
{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"admin@mailserver1",
"[email protected]",
"\" \"@example.org",
"\"john..doe\"@example.org"
};
var invalidEmails = new string[]
{
"Abc.example.com",
"A@b@[email protected]",
"a\"b(c)d,e:f;g<h>i[j\\k][email protected]",
"just\"not\"[email protected]",
"this is\"not\\[email protected]",
"this\\ still\\\"not\\\\[email protected]",
"1234567890123456789012345678901234567890123456789012345678901234+x@example.com"
};
Console.WriteLine(validEmails.All(x => A(x))); // true
Console.WriteLine(validEmails.All(x => B(x))); // false
Console.WriteLine(invalidEmails.All(x => !A(x))); // false
Console.WriteLine(invalidEmails.All(x => !B(x))); // true
}
}
Jeżeli chodzi o poprawne adresy, to metoda A
łapie je wszystkie dobrze, ale przy sprawdzaniu listy niepoprawnych jest jeden wyjątek
Adres 1234567890123456789012345678901234567890123456789012345678901234+x@example.com
jest według metody A
poprawny, chociaż początek nie powinien przekraczać 64 znaków.
Raczej używałbym A
edit. poprawiłem escapy.