rubyregexemail-parsing

How do I write this regex in ruby? (parsing Gmail API fields)


I have 3 types of strings I need to parse:

"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>"

I need a hash of each, that looks like:

{ '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

Solution

  • You can use mail gem to parse.

    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}}
    

    The same thread: stackoverflow thread