使用正则表达式的Ruby电子邮件验证 [英] Ruby Email validation with regex

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

问题描述

我有一大笔电子邮件列表。很多电子邮件都有打字错误。我正在尝试构建一个字符串来检查有效的电子邮件。



这是正则表达式。

  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-Z‌​a-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆