Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何使用正则表达式解析带引号的搜索字符串?_Ruby_Regex - Fatal编程技术网

Ruby 如何使用正则表达式解析带引号的搜索字符串?

Ruby 如何使用正则表达式解析带引号的搜索字符串?,ruby,regex,Ruby,Regex,给定搜索字符串cars'cats and dogs'fish'hammers,捕获所有搜索词的最佳正则表达式是什么。它应该支持单引号和双引号。如果可能的话,提供一个Ruby友好的答案。使用Stringscan: 哦,为了去掉结果中的引号: irb> ["cars", "'cats and dogs'", "fish", "'hammers'"].map { |s| s.gsub /^['"]|['"]$/, '' } => ["cars", "cats and dogs", "f

给定搜索字符串cars'cats and dogs'fish'hammers,捕获所有搜索词的最佳正则表达式是什么。它应该支持单引号和双引号。如果可能的话,提供一个Ruby友好的答案。

使用Stringscan:

哦,为了去掉结果中的引号:

irb> ["cars", "'cats and dogs'", "fish", "'hammers'"].map { |s| s.gsub /^['"]|['"]$/, '' }
  => ["cars", "cats and dogs", "fish", "hammers"]

那筑巢汽车、猫和狗呢?是的,这是另一个需要解决的问题。这是可行的,我可以使用它,但我想在没有地图的情况下完成这项工作。我有一个正则表达式几乎可以做到这一点,但它在引用的短语上捕获了一个额外的引号:/?\s*\b\s[^\1]*?\b\s*\1/s.scan/'.+?'.+?'.+?[^]+/.flatte.compact将排除引号。@Wayne,这不起作用。它删除了所有的引语,包括那些围绕着“狗和猫”这样的搜索短语的引语。@Gavin,从你之前的评论来看,这就是我认为你想要的。对不起,我误解了。你的问题有样本输入;如果它有该输入的输出,那就好了。@Wayne,输入:cars'cats and dogs'fish'hammers',输出:[cars,cats and dogs,fish,hammers]
irb> ["cars", "'cats and dogs'", "fish", "'hammers'"].map { |s| s.gsub /^['"]|['"]$/, '' }
  => ["cars", "cats and dogs", "fish", "hammers"]