假设您的数据遵循您提供的示例,这应该有效:
def extract_emails(string)
string.split(', ').map do |user_string|
if user_string.include? '<'
user_string =~ /^([^<]*)<([^>]*)>$/
{user: $1.strip, email: $2}
else
{user: nil, email: user_string}
end
end
end
extract_emails "a@a.com"
# => [{:user=>nil, :email=>"a@a.com"}]
extract_emails "a@a.com, Bob Blue <b@b.com>"
# => [{:user=>nil, :email=>"a@a.com"}, {:user=>"Bob Blue", :email=>"b@b.com"}]
extract_emails "Abe Allen <a@a.com>, b@b.com"
# => [{:user=>"Abe Allen", :email=>"a@a.com"}, {:user=>nil, :email=>"b@b.com"}]
extract_emails "Abe Allen <a@a.com>, Bob Blue <b@b.com>"
# => [{:user=>"Abe Allen", :email=>"a@a.com"}, {:user=>"Bob Blue", :email=>"b@b.com"}]
extract_emails "Abe Allen <a@a.com>, Bob Blue <b@b.com>, c@c.com"
# => [{:user=>"Abe Allen", :email=>"a@a.com"}, {:user=>"Bob Blue", :email=>"b@b.com"}, {:user=>nil, :email=>"c@c.com"}]