使用正则表达式的Ruby电子邮件验证 [英] Ruby Email validation with regex
问题描述
这是正则表达式。
def is_a_valid_email? (电子邮件)
(email =〜/^((CA-Za-z0-9]*\.+*_+)|([A-Za-z0-9]+\\+++) |([A-ZA-Z0-9] + \ +)|([A-ZA-Z0-9] + \ +))* [A-Z A-Z0-9] + @ {1} ((\w + \ - +)|(\w + \。))* \w {1,63} \。[a-zA-Z] {2,4} $ / i)
end
如果电子邮件的下划线和只有一个周期,则会传递。我有很多电子邮件,在这个名字本身有一段时间。如何在正则表达式中检查。
hello.me_1@email.com#< ~~ valid
foo.bar#gmail.co.uk #< ~~~ valid
foobar@gmail.com#< ~~~ valid
f ... bar@gmail.com#< ~~无效
get_at_m.e @gmail#< ~~有效
有人可以帮我重写我的正则表达式吗?
TL; DR:
VALID_EMAIL_REGEX = / \A [\w + \ - 。] + @ [az\d\ - ] +(\。[az\d\ - ] +)* \。 az] + \z / i
原始答案
你似乎使事情变得复杂了,我只会使用:
VALID_EMAIL_REGEX = / \A [\\ \\ w + \ - 。] + @ [az\d\ - ] +(\。[az] +)* \。[az] + \z / i
因为这不符合你的点要求,它可以简单地被修改如下:
VALID_EMAIL_REGEX = /\A([\w+\-]\.?)+@[az\d\-] +(\。[az] +)* \。[az] + \z / i
正如CAustin所提到的,还有许多其他解决方案。
编辑:
由@installero指出,原始版本的子域名中的连字符失败,此版本将会工作(不知道为什么字符类缺少数字和连字符在第一位)。
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[az \d\ - ] +(\。[az\d\ - ] +)* \。[az] + \z / i
I have a large list of emails I am running through. A lot of the emails have typos. I am trying to build a string that will check valid emails.
this is what I have for regex.
def is_a_valid_email?(email)
(email =~ /^(([A-Za-z0-9]*\.+*_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\+)|([A-Za-z0-9]+\+))*[A-Za-z0-9]+@{1}((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,4}$/i)
end
It passes if an email as underscores and only one period. I have a lot of emails that have more then one periods in the name itself. How do I check that in regex.
hello.me_1@email.com # <~~ valid
foo.bar#gmail.co.uk # <~~~valid
f.o.o.b.a.r@gmail.com # <~~~valid
f...bar@gmail.com # <~~ not valid
get_at_m.e@gmail #<~~ valid
Can someone help me rewrite my regex ?
TL;DR:
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
Original answer
You seem to be complicating things a lot, I would simply use:
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
which is taken from michael hartl's rails book
since this doesn't meet your dot requirement it can simply be ammended like so:
VALID_EMAIL_REGEX = /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
As mentioned by CAustin, there are many other solutions.
EDIT:
it was pointed out by @installero that the original fails for subdomains with hyphens in them, this version will work (not sure why the character class was missing digits and hyphens in the first place).
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
这篇关于使用正则表达式的Ruby电子邮件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!