C#/.NET/.NET Core应用程序编程开发中如何判断/验证字符串是电子邮箱格式呢?
3 个回答
-
如果是.NET 4.5 +,可以使用命名空间
System.ComponentModel.DataAnnotations
的EmailAddress
特性标记来判断指定的字符串是否是正确的电子邮箱格式,如下:using System.ComponentModel.DataAnnotations; class ValidateSomeEmails { static void Main(string[] args) { var foo = new EmailAddressAttribute(); bool bar; bar = foo.IsValid("someone@somewhere.com"); //true bar = foo.IsValid("someone@somewhere.co.uk"); //true bar = foo.IsValid("someone+tag@somewhere.net"); //true bar = foo.IsValid("futureTLD@somewhere.fooo"); //true bar = foo.IsValid("fdsa"); //false bar = foo.IsValid("fdsa@"); //false bar = foo.IsValid("fdsa@fdsa"); //false bar = foo.IsValid("fdsa@fdsa."); //false if (new EmailAddressAttribute().IsValid("someone@somewhere.com")) bar = true; } }
-
使用正则表达式来验证指定的字符串是否是正确的电子邮箱格式,如下:
using System.Text.RegularExpressions; public static class Validator { static Regex ValidEmailRegex = CreateValidEmailRegex(); private static Regex CreateValidEmailRegex() { string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$"; return new Regex(validEmailPattern, RegexOptions.IgnoreCase); } internal static bool EmailIsValid(string emailAddress) { bool isValid = ValidEmailRegex.IsMatch(emailAddress); return isValid; } }