开发者

How to parse a quoted search string using regex?

开发者 https://www.devze.com 2023-01-06 21:13 出处:网络
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 ans

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

精彩评论

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