Created
April 11, 2012 16:50
-
-
Save aantix/2360476 to your computer and use it in GitHub Desktop.
Extract Names and Emails Address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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