2

我需要解析 3 种类型的字符串:

"John Smith <jsmith@gmail.com>"

"\"jsmith@gmail.com\" <jsmith@gmail.com>, \"bob@gmail.com\" <bob@gmail.com>"

"\"yo@gmail.com\" <yo@gmail.com>, John Smith <jsmith@gmial.com>"

我需要每个的哈希,看起来像:

{ 'John Smith' => 'jsmith@gmail.com' } # for the first one

{ 'jsmith@gmail.com' => 'jsmith@gmail.com', 'bob@gmail.com' => 'bob@gmail.com' } # for the second one

{ 'yo@gmail.com' => 'yo@gmail.com', 'John Smith' => 'jsmith@gmail.com' } # for the third one
4

3 回答 3

1

您可以使用邮件gem 进行解析。

emails = "\"jsmith@gmail.com\" <jsmith@gmail.com>, \"bob@gmail.com\" <bob@gmail.com>, \"Bobby\" <bobby@gmail.com>"

raw_addresses = Mail::AddressList.new(emails)

result = raw_addresses.addresses.map {|a| {name: a.name, email: a.address}}

同一个线程:stackoverflow线程

于 2015-04-27T23:03:41.283 回答
1

这是一个正则表达式,不需要宝石...

它可能需要一些测试,但似乎还可以。

str = "yo0@gmail.com; yo1@gmail.com, \"yo2@gmail.com\" <yo@gmail.com>, John Smith <jsmith@gmial.com>"

str.split(/[\s]*[,;][\s]*/).each.with_object({}) {|addr, hash| a = addr.match(/[\"]?([^\"\<]*)[\"]?[\s]*\<([\w@\w\.]+)\>/) ; a ? hash[a[1].strip] = a[2]: hash[addr] = addr}

# => {"yo0@gmail.com"=>"yo0@gmail.com", "yo1@gmail.com"=>"yo1@gmail.com",
#     "yo2@gmail.com"=>"yo@gmail.com", "John Smith"=>"jsmith@gmial.com"}

请注意,哈希不会包含两个相同的键 - 因此使用哈希可能会导致数据丢失!

考虑以下情况:

  1. 一个人有两个电子邮件地址。

  2. 两个同名但电子邮件地址不同的人。

这两种情况在使用哈希时都会导致数据丢失,而不是使用数组。数组数组和哈希数组都可以很好地工作。

观察:

str = "John Smith <email1@gmail.com>, John Smith <another_address@gmail.com>"

str.split(/[\s]*[,;][\s]*/).each.with_object({}) {|addr, hash| a = addr.match(/[\"]?([^\"\<]*)[\"]?[\s]*\<([\w@\w\.]+)\>/) ; a ? hash[a[1].strip] = a[2]: hash[addr] = addr}

#  => {"John Smith"=>"another_address@gmail.com"}
# Only ONE email extracted.

str.split(/[\s]*[,;][\s]*/).each.with_object([]) {|addr, arry| a = addr.match(/[\"]?([^\"\<]*)[\"]?[\s]*\<([\w@\w\.]+)\>/) ; a ? arry << [ a[1].strip, a[2] ]: [ addr, addr ]}

#  => [["John Smith", "email1@gmail.com"], ["John Smith", "another_address@gmail.com"]] 
# Both addresses extracted.

str.split(/[\s]*[,;][\s]*/).each.with_object([]) {|addr, arry| a = addr.match(/[\"]?([^\"\<]*)[\"]?[\s]*\<([\w@\w\.]+)\>/) ; a ? arry << {name: a[1].strip, email: a[2] }: {email: addr} }

# => [{:name=>"John Smith", :email=>"email1@gmail.com"}, {:name=>"John Smith", :email=>"another_address@gmail.com"}] 
# Both addresses extracted.

祝你好运!

于 2015-04-28T02:24:26.707 回答
0
myHash = {}
str = "\"vishal@sendsonar.com\" <vishal@sendsonar.com>, Michael Makarov <michael@sendsonar.com>"
str.strip.split(',').map{|x| x.strip}.each do |contact|
  parts = contact.scan(/"{0,1}(.*?)"{0,1} <(.*?)>/)
  myHash[parts[0][0]] = parts[0][1]
end
于 2015-04-27T23:11:31.483 回答