问题描述
我正在 VB.Net 中处理一个小项目,我从文本框中获取输入,并需要验证这是一个电子邮件地址.
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.
我发现这个表达式 "^[_a-z0-9-]+(.[_a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)(.[az]{2,4})$",但我找不到任何方法来测试它是否通过.
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
推荐答案
使用 System.Text.RegularExpressions.Regex
类:
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
了解这个答案最重要的一点是,正则表达式不是我自己写的.有很多错误的方法似乎是正确的,并且您可以将其带到几个级别的细节.例如,您是否希望将其限制为有效的顶级域,如果是,您如何解释他们现在偶尔会添加新 TLD 的事实?如果正则表达式最适合那个测试的地方,还是应该有单独的代码进行那个检查?甚至这个答案中的表达现在也非常陈旧,因为它最初是创作的.
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.
我建议为您知道会随着时间推移而维护的表达式寻找外部资源.
I recommend finding an outside resource for the expression you know will be maintained over time.
这篇关于使用正则表达式 VB.Net 验证电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!