我正在尝试将类似于“测试驱动开发”的演示文稿的字符串拆分为如下数组:
- [ 'Presentation','about','"Behavior Driven Development"' ]
我试过了CSV :: parse_line(string,col_sep:”),但结果却是这样
- [ 'Presentation','Behavior Driven Development' ] # I'm missing the quotes here
我也试过一些正则表达式的魔法,但我还是初学者并没有成功.我想对于专业人士来说这很简单,所以也许有人可以指出我正确的方向?谢谢.
解决方法
您可以使用以下正则表达式
split
:
- str = 'Presentation about "Test Driven Development"'
- p str.split(/\s(?=(?:[^"]|"[^"]*")*$)/)
- # => ["Presentation","about","\"Test Driven Development\""]
如果有空格,它会分裂,但只有在结尾之后的文本包含偶数“.请注意,只有在所有字符串都被正确引用时,此版本才会起作用.
- p str.scan(/(?:\w|"[^"]*")+/)
- # => ["Presentation","\"Test Driven Development\""]