如何验证使用正则表达式尾句号电子邮件地址?
问题描述:
下面的正则表达式不验证如果电子邮件地址有在最后一个句号。 E.G [email protected]。 如果我通过这个电子邮件地址作为参数strEmail
向IsValidEmailAddress函数,该函数将返回true
。它应该返回false
。如何验证使用正则表达式尾句号电子邮件地址?
const string MatchEmailPattern = @"(([\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})";
private bool IsValidEmailAddress(string strEmail)
{
System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(strEmail.Trim().ToLower(), MatchEmailPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (!match.Success)
{
return false;
}
return true;
}
我非常感谢关于如何处理尾随句号的建议。
答
您需要令牌“字符串的结束”添加到你的正则表达式模式
const string MatchEmailPattern = @"(([\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})$";
...并使它到最后,还添加了“字符串的开始”令牌:
const string MatchEmailPattern = @"^(([\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})$";
https://msdn.microsoft.com/en-us/library/01escwtf(v=vs.110).aspx – bolov
http://stackoverflow.com/questions/1365407/c-sharp-code-to-验证电子邮件地址 – bolov