验证字符串是否是有效的电子邮件地址的最优雅的代码是什么?
当前回答
一般来说,使用正则表达式来验证电子邮件地址并不是一件容易的事情;在撰写本文时,电子邮件地址的语法必须遵循相对较多的标准,在正则表达式中实现所有这些标准实际上是不可行的!
我强烈建议你试试我们的EmailVerify。NET是一个成熟的。NET库,它可以根据当前所有的IETF标准(RFC 1123, RFC 2821, RFC 2822, RFC 3696, RFC 4291, RFC 5321和RFC 5322)验证电子邮件地址,测试相关的DNS记录,检查目标邮箱是否可以接受消息,甚至可以判断给定的地址是否是一次性的。
免责声明:我是这个组件的主要开发人员。
其他回答
电子邮件地址验证并不像看起来那么简单。实际上,从理论上讲,仅使用正则表达式完全验证电子邮件地址是不可能的。
请查看我的博客文章,了解关于这个主题的讨论以及使用FParsec的f#实现。[/ shameless_plug]
我只是想指出,最近在. net文档中增加了关于电子邮件验证的内容,也使用了Regex操作。 关于它们实现的详细解释可以在那里找到。
https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format
为了方便起见,下面是他们的测试结果:
// Valid: david.jones@proseware.com
// Valid: d.j@server1.proseware.com
// Valid: jones@ms1.proseware.com
// Invalid: j.@server1.proseware.com
// Valid: j@proseware.com9
// Valid: js#internal@proseware.com
// Valid: j_9@[129.126.118.1]
// Invalid: j..s@proseware.com
// Invalid: js*@proseware.com
// Invalid: js@proseware..com
// Valid: js@proseware.com9
// Valid: j.s@server1.proseware.com
// Valid: "j\"s\""@proseware.com
// Valid: js@contoso.中国
我最终使用了这个正则表达式,因为它成功地验证了逗号、注释、Unicode字符和IP(v4)域地址。
有效地址为:
“@example。org (评论)test@example。org тест@example。org ტესტი@example。org test@[192.168 . 1章1段]
public const string REGEX_EMAIL = @"^(((\([\w!#$%&'*+\/=?^_`{|}~-]*\))?[^<>()[\]\\.,;:\s@\""]+(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))(\([\w!#$%&'*+\/=?^_`{|}~-]*\))?@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$";
短而准确的代码
string Email = txtEmail.Text;
if (Email.IsValidEmail())
{
//use code here
}
public static bool IsValidEmail(this string email)
{
string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(email);
}
这可能是对文本框进行电子邮件验证的最佳方式。
string pattern = null;
pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
if (Regex.IsMatch("txtemail.Text", pattern))
{
MessageBox.Show ("Valid Email address ");
}
else
{
MessageBox.Show("Invalid Email Email");
}
只要在任何你想要的函数中包含。
推荐文章
- 用c#创建一个空文件
- 流。Seek(0, SeekOrigin.Begin)或Position = 0
- 如果查询为空,则最大返回值
- "输出类型为类库的项目不能直接启动"
- 传递一个实例化的系统。类型作为泛型类的类型参数
- 从SqlCommand对象获取生成的SQL语句?
- 把内容放在HttpResponseMessage对象?
- 在c#中转换字符串为类型
- 如何比较单元测试中的列表
- 替换c#字符串中的多个字符
- 将XML字符串转换为对象
- ToList()——它是否创建一个新列表?
- 连接网络共享时,如何提供用户名和密码
- ProcessStartInfo挂在“WaitForExit”?为什么?
- 我如何通过Java应用程序使用GMail,雅虎或Hotmail发送电子邮件?