开发者

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"]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜