鉴于搜索字符串“汽车'猫和狗'鱼'锤'',什么是捕获所有搜索词的最佳正则表达式。它应该支持单引号和双引号。如果可能的话,Ruby友好的答案。
答案 0 :(得分:8)
使用String#scan
:
irb> "cars 'cats and dogs' fish 'hammers'".scan /'.+?'|".+?"|[^ ]+/
=> ["cars", "'cats and dogs'", "fish", "'hammers'"]
哦,并在结果中删除周围的引号:
irb> ["cars", "'cats and dogs'", "fish", "'hammers'"].map { |s| s.gsub /^['"]|['"]$/, '' }
=> ["cars", "cats and dogs", "fish", "hammers"]