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

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

问题描述

我有一大堆正在浏览的电子邮件.很多邮件都有错别字.我正在尝试构建一个将检查有效电子邮件的字符串.

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 # <~~~ not 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:

归功于@joshuahunter(在下面,支持他的回答).包括在这里,以便人们看到它.

TL;DR:

credit goes to @joshuahunter (below, upvote his answer). Included here so that people see it.

URI::MailTo::EMAIL_REGEXP

老 TL;DR

VALID_EMAIL_REGEX = /A[w+-.]+@[a-zd-]+(.[a-zd-]+)*.[a-z]+z/i

原答案

你似乎把事情复杂化了很多,我只会用:

Original answer

You seem to be complicating things a lot, I would simply use:

VALID_EMAIL_REGEX = /A[w+-.]+@[a-zd-]+(.[a-z]+)*.[a-z]+z/i

摘自 michael hartl 的 rails book

由于这不符合您的点要求,因此可以简单地像这样修改:

since this doesn't meet your dot requirement it can simply be ammended like so:

VALID_EMAIL_REGEX = /A([w+-].?)+@[a-zd-]+(.[a-z]+)*.[a-z]+z/i

正如 CAustin 所说,还有很多其他的解决方案.

As mentioned by CAustin, there are many other solutions.

@installero 指出,对于包含连字符的子域,原始版本失败,此版本将起作用(不确定为什么字符类首先缺少数字和连字符).

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-zd-]+(.[a-zd-]+)*.[a-z]+z/i

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

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