這個問題本身並不是一個答案,但如果有人需要,我寫了一個C#函數來驗證使用此方法的電子郵件地址。
FixEmailAddress("[email protected]")
回報"[email protected]"
FixEmailAddress("[email protected]@xyz.com,[email protected],asdfdsf,[email protected]")
回報"[email protected],[email protected]"
我處理電子郵件地址列表這種方式,因爲用逗號分隔的電子郵件列表是MailAddressCollection.Add(有效的參數)
/// <summary>
/// Given a single email address, return the email address if it is valid, or empty string if invalid.
/// or given a comma delimited list of email addresses, return the a comma list of valid email addresses from the original list.
/// </summary>
/// <param name="emailAddess"></param>
/// <returns>Validated email address(es)</returns>
public static string FixEmailAddress(string emailAddress)
{
string result = "";
emailAddress = emailAddress.Replace(";",",");
if (emailAddress.Contains(","))
{
List<string> results = new List<string>();
string[] emailAddresses = emailAddress.Split(new char[] { ',' });
foreach (string e in emailAddresses)
{
string temp = FixEmailAddress(e);
if (temp != "")
{
results.Add(temp);
}
}
result = string.Join(",", results);
}
else
{
try
{
System.Net.Mail.MailAddress email = new System.Net.Mail.MailAddress(emailAddress);
result = email.Address;
}
catch (Exception)
{
result = "";
}
}
return result;
}
你有沒有嘗試使用反編譯器,看看有什麼'MailAddress'使用? – Oded
@Oded:我有。它使用一個叫做MailBnfHelper的大型內部類,它在.Net 4.0中發生了很大的變化。我不建議提取它。 – SLaks
.Net框架的不同版本使用不同的規則來支持它,所以我會擔心你創建的任何正則表達式可能不是未來的證明。雖然我同意SLaks的答案,但是「Try Catch」將會是未來的證明。否則,如果你真的想寫一個正則表達式,[MailAddress](http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddress.aspx)的文檔描述了它使用的規則,所以你可能能夠以此爲起點。 –