Skip to content

Instantly share code, notes, and snippets.

@aantix
Created April 11, 2012 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aantix/2360476 to your computer and use it in GitHub Desktop.
Save aantix/2360476 to your computer and use it in GitHub Desktop.
Extract Names and Emails Address
# http://zadasnotes.blogspot.ca/2012/04/extracting-names-and-email-addresses.html
# first last <email1@example.com>
# {:name => "First Last", :email => "email1@example.com"}
# john.smith@example.com
# {:name => "John Smith", :email => "john.smith@example.com"}
# mary@example.com
# {:name => "Mary", :email => "mary@example.com"}
def names_and_emails_from_multiple_addresses(emails)
addresses = emails.split(',')
result = Array.new
addresses.each do |address|
next if address.blank?
matches = address.strip.scan(/(\w[^<\>]*)<(\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b)\>\z|\A<!--?((\b[A-Z0-9._%+-]+)@[A-Z0-9.-]+\.[A-Z]{2,4}\b)-->?\z/i)
if matches[0] && matches[0][1]
email = matches[0][1]
name = matches[0][0]
elsif matches[0] && matches[0][2]
email = matches[0][2]
name = matches [0][3]
end
if email.blank? || name.blank?
return nil
else
result << {:email => email.downcase.strip, :name => name.gsub(/\./, ' ').titleize.strip}
end
end
return result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment