试图将字符串拆分为单个单词或"引用的单词",并希望在结果数组中保留引号

Jos*_*eim 7 ruby regex csv

我正在尝试将字符串拆分Presentation about "Test Driven Development"为如下数组:

[ 'Presentation',
  'about',
  '"Behavior Driven Development"' ]
Run Code Online (Sandbox Code Playgroud)

我试过了CSV::parse_line(string, col_sep: ' '),但这导致了

[ 'Presentation',
  'about',
  'Behavior Driven Development' ] # I'm missing the quotes here
Run Code Online (Sandbox Code Playgroud)

我也试过一些正则表达式的魔法,但我还是初学者并没有成功.我想对于专业人士来说这很简单,所以也许有人可以指出我正确的方向?谢谢.

How*_*ard 16

您可以使用以下正则表达式split:

str = 'Presentation about "Test Driven Development"'
p str.split(/\s(?=(?:[^"]|"[^"]*")*$)/)
# => ["Presentation", "about", "\"Test Driven Development\""]
Run Code Online (Sandbox Code Playgroud)

如果有空格,它会分裂,但只有直到结尾的文本包含偶数".请注意,只有正确引用所有字符串时,此版本才有效.

另一种解决方案用于scan读取字符串的部分(除了空格):

p str.scan(/(?:\w|"[^"]*")+/)
# => ["Presentation", "about", "\"Test Driven Development\""]
Run Code Online (Sandbox Code Playgroud)