2016-03-03 33 views
1

我有一个带有文本字段的表单,用户可以在其中输入多个电子邮件地址。问题是,这些电子邮件地址的格式有很多不同的方式。例如:从文本字段获取电子邮件地址,无论格式如何

emails = params[:invite][:invite_emails].split(', ') 
emails.each do |email| 
    # send_email 
end 

我怎么能得到所有的电子邮件,即使他们格式不同:

"Bob Smith" <[email protected]>, [email protected], "John Doe"<[email protected]> 

现在,我用它们分开?

+0

这可能不是一个好主意,使用这个正则表达式:http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address?rq=1 –

+0

我同意!如果可能的话,会很乐意去做。 – alejoriveralara

+0

我误解了,你已经添加了标签“正则表达式”,我以为你正在寻找正则表达式的解决方案;-) –

回答

2

没有绝对的解析电子邮件的方法。但是,我们可以试图掩盖一些很好的理由:

s = '"Bob Smith" <[email protected]>, [email protected], "John Doe"<[email protected]>' 
s.scan(/\[email protected]\w+\.\w+/) 
#=> ["[email protected]", "[email protected]", "[email protected]"] 

这将覆盖通用顶级域名以及:

s = '"Bob Smith" <[email protected]>, [email protected], "John Doe"<[email protected]> [email protected]' 
s.scan(/\[email protected]\w+\.\w+[\.\w]{0,4}/) 
#=> ["[email protected]", "[email protected]", "[email protected]", "[email protected]"] 

如果您还有其他特殊情况下,你只需要调整的一个正则表达式位。

+0

这很好,我不知道扫描方法。谢谢! – alejoriveralara

相关问题