验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?
当前回答
There are a lot of strong answers here. However, I recommend that we take a step back. @Cogwheel answers the question https://stackoverflow.com/a/1374644/388267. Nevertheless, it could be costly in a bulk validation scenario, if many of the email address being validated are invalid. I suggest that we employ a bit of logic before we enter into his try-catch block. I know that the following code could be written using RegEx but that could be costly for new developers to understand. This is my twopence worth:
public static bool IsEmail(this string input)
{
if (string.IsNullOrWhiteSpace(input)) return false;
// MUST CONTAIN ONE AND ONLY ONE @
var atCount = input.Count(c => c == '@');
if (atCount != 1) return false;
// MUST CONTAIN PERIOD
if (!input.Contains(".")) return false;
// @ MUST OCCUR BEFORE LAST PERIOD
var indexOfAt = input.IndexOf("@", StringComparison.Ordinal);
var lastIndexOfPeriod = input.LastIndexOf(".", StringComparison.Ordinal);
var atBeforeLastPeriod = lastIndexOfPeriod > indexOfAt;
if (!atBeforeLastPeriod) return false;
// CODE FROM COGWHEEL'S ANSWER: https://stackoverflow.com/a/1374644/388267
try
{
var addr = new System.Net.Mail.MailAddress(input);
return addr.Address == input;
}
catch
{
return false;
}
}
其他回答
public static bool IsEmail(string strEmail)
{
Regex rgxEmail = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
return rgxEmail.IsMatch(strEmail);
}
来自@齿轮的投票最多的答案是最好的答案,但我已经尝试实现trim()字符串方法,因此它将从字符串开始到结束修剪所有用户空白。检查代码下面的完整示例-
bool IsValidEmail(string email)
{
try
{
email = email.Trim();
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}
另一个正则表达式匹配答案:
/// <summary>
/// Validates the email input
/// </summary>
internal static bool ValidateEmail(string _emailAddress)
{
string _regexPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
return (string.IsNullOrEmpty(_emailAddress) == false && System.Text.RegularExpressions.Regex.IsMatch(_emailAddress, _regexPattern))
? true
: false;
}
我将Poyson 1的答案简化如下:
public static bool IsValidEmailAddress(string candidateEmailAddr)
{
string regexExpresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
return (Regex.IsMatch(candidateEmailAddr, regexExpresion)) &&
(Regex.Replace(candidateEmailAddr, regexExpresion, string.Empty).Length == 0);
}
private static bool IsValidEmail(string emailAddress)
{
const 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).IsMatch(emailAddress);
}
推荐文章
- 在c#中从URI字符串获取文件名
- 检查SqlDataReader对象中的列名
- 如何将类标记为已弃用?
- c# 8支持。net框架吗?
- Linq-to-Entities Join vs GroupJoin
- 为什么字符串类型的默认值是null而不是空字符串?
- 在list中获取不同值的列表
- 组合框:向项目添加文本和值(无绑定源)
- 如何为ASP.net/C#应用程序配置文件值中的值添加&号
- 从System.Drawing.Bitmap中加载WPF BitmapImage
- 如何找出一个文件存在于c# / .NET?
- 为什么更快地检查字典是否包含键,而不是捕捉异常,以防它不?
- [DataContract]的命名空间
- string. isnullorempty (string) vs. string. isnullowhitespace (string)
- 完全外部连接