本文介绍了使用正则表达式VB.Net验证电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在VB.Net中的一个小项目中,从文本框中获取输入,需要验证这是一个电子邮件地址。



<我发现这个表达式^ [_ a-z0-9 - ] +(。[_ a-z0-9 - ] +) @ [a-z0-9 - ] +(。[a-z0-9 - ] +)(。[az] {2,4})$,但我无法找到任何方法来测试是否通过。



想要一些代码,如:

 如果不是txtEmail.text = regexString然后
某事发生..
else
其他事情发生..
结束如果


解决方案

使用 System.Text.RegularExpressions.Regex class:

 函数IsEmail(Byval email as string)as boolean 
静态emailExpression为新正则表达式(^ [_ a-z0-9 - ] +(。[a-z0-9 - ] +)@ [a-z0 -9 - ] +(。[a-z0-9 - ] +)*(。[az] {2,4})$)

return emailExpression.IsMatch(email)
结束功能

了解这个答案最重要的是我没有自己习惯正则表达式。只有这么多错误的方式似乎是正确的,有几个级别的细节,你可以采取这一点。例如,您是否要将此限制为有效的顶级域名,如果是这样,那么您如何处理他们现在偶尔添加新TLD的事实呢?如果正则表达式是该测试最合适的地方,还是应该有单独的代码用于该检查?即使在这个答案中的表达方式现在非常陈旧,因为它是最初创作的。我建议您找到一个资源,您可以使用该资源为您所知道的表达式进行维护。


I'm working on a small project in VB.Net where I get a input from a textbox, and need to verify that this is an e-email address.

I found this expression "^[_a-z0-9-]+(.[_a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)(.[a-z]{2,4})$", but i cant find any way to test if it passes.

I want some code like:

if not txtEmail.text = regexString then
    something happens..
else
    something else happens..
end if
解决方案

Use the System.Text.RegularExpressions.Regex class:

Function IsEmail(Byval email as string) as boolean
    Static emailExpression As New Regex("^[_a-z0-9-]+(.[a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$")

    return emailExpression.IsMatch(email)
End Function

The most important thing to understand about this answer is that I didn't write the regular expression myself. There are just so many wrong ways that seem to be right, and there are several levels of detail that you could take this to. For example, do you want to restrict this to valid top level domains, and if so, how are you accounting for the fact that they are now occasionally adding new TLDs? If the regular expression the most appropriate place for that test, or should have separate code for that check? Even the expression in this answer is now very stale since it was originally authored. What I recommend is to find a resource that you can use for the expression that you know will be maintained.

这篇关于使用正则表达式VB.Net验证电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 09:49