如何在ruby中编写这个正则表达式? (解析Gmail API字段)

时间:2015-04-27 22:23:40

标签: ruby regex email-parsing

我需要解析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

3 个答案:

答案 0 :(得分:1)

您可以使用mail 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 thread

答案 1 :(得分:1)

这里是Regexp,不需要任何宝石......

它可能需要一些测试,但似乎没问题。

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. 两个人姓名相同但电子邮件地址不同的人。

  3. 使用Hash时,两种情况都会导致数据丢失,而不是使用数组。数组数组和哈希数组都可以正常工作。

    观察:

    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.
    

    祝你好运!

答案 2 :(得分: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