Skip to content

Instantly share code, notes, and snippets.

@aantix
Created April 11, 2012 16:50
Show Gist options
  • 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 <[email protected]>
# {:name => "First Last", :email => "[email protected]"}
# [email protected]
# {:name => "John Smith", :email => "[email protected]"}
# [email protected]
# {:name => "Mary", :email => "[email protected]"}
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