Search code examples
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 <[email protected]>"

"\"[email protected]\" <[email protected]>, \"[email protected]\" <[email protected]>"

"\"[email protected]\" <[email protected]>, John Smith <[email protected]>"

I need a hash of each, that looks like:

{ 'John Smith' => '[email protected]' } # for the first one

{ '[email protected]' => '[email protected]', '[email protected]' => '[email protected]' } # for the second one

{ '[email protected]' => '[email protected]', 'John Smith' => '[email protected]' } # for the third one

Solution

  • You can use mail gem to parse.

    emails = "\"[email protected]\" <[email protected]>, \"[email protected]\" <[email protected]>, \"Bobby\" <[email protected]>"
    
    raw_addresses = Mail::AddressList.new(emails)
    
    result = raw_addresses.addresses.map {|a| {name: a.name, email: a.address}}
    

    The same thread: stackoverflow thread