开发者

Need to wrap certain parts of a string of email addresses in quotes

Given a string such as this:

Bob Smith <bobsmith@gmail.com>, Jones, Rich A. <richjones@gmail.com>

I need to produce a string like this:

Bob Smith <bobsmith@gmail.com>, "Jones, Rich A." <richjones@gmail.com>

Or alternatively (if this is easier):

"Bob Smith" <bobsmith@gmail.c开发者_Python百科om>, "Jones, Rich A." <richjones@gmail.com>

What's the most elegant way to do this in Ruby?


You can do gsub, or scan. Either way a regex is most elegant. I recommend a scan, so you will have the option to go through each email address and do whatever you want to it (including deciding whether or not to quote the name).

str = Bob Smith <bobsmith@gmail.com>, Jones, Rich A. <richjones@gmail.com>
email_addrs = []

str.scan(/\s*(.*?)\s*<(.+?)>(?:,|\Z)/) do |match|
  # yields ["Bob Smith", "bobsmith@gmail.com"]
  # then   ["Jones, Rich A.", "richjones@gmail.com"]

  email_addrs << "\"#{match.first}\" <#{match.last}>"
end

email_addrs.join(", ") #=> "Bob Smith" <bobsmith@gmail.com>, "Jones, Rich A." <richjones@gmail.com>

Good luck!


You could get fancy with a regex, and I'm sure someone will spend the time to build one, but if you want something that makes sense:

# s is the string
def add_quotes(s)
  s = s.split
  new_s = []
  s.each do |w|
    unless w.index('<') == 0 && w.index('>') == w.length-1
      new_s << "\"#{w}\""
    else
      new_s << w
    end
  end

  new_s.join(' ')
end


Build a regular expression that matches the "names", and replace each occurrence in a loop with the same string enclosed in quotes. Look at the String class and the regex matchers, especially the ones that iterate over the matches.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜