How to parse a quoted search string using regex?
Given a search string "cars 'cats and dogs' f开发者_Python百科ish 'hammers'", what's the best regex for capturing all search terms. It should support single and double quotes. A Ruby friendly answer if possible.
Using String#scan
:
irb> "cars 'cats and dogs' fish 'hammers'".scan /'.+?'|".+?"|[^ ]+/
=> ["cars", "'cats and dogs'", "fish", "'hammers'"]
Oh, and to get rid of surrounding quotes in the result:
irb> ["cars", "'cats and dogs'", "fish", "'hammers'"].map { |s| s.gsub /^['"]|['"]$/, '' }
=> ["cars", "cats and dogs", "fish", "hammers"]
精彩评论