字符串到数组基于关闭双引号

时间:2013-11-04 15:04:40

标签: ruby

我正在尝试转换此字符串:

'"This is a normal string","This, has a comma inside it"'

string.split(",")加入数组,但是我得到三个,而不是在数组中得到两个元素:

["This is a normal string","This","has a comma inside it"]

有关可能的解决方案的任何建议吗?如何在结束双引号而不是逗号分割字符串?

1 个答案:

答案 0 :(得分:3)

认为扫描方法可能是最简单的方法:

s.scan(/"(.*?)"/).flatten #=> ["This is a normal string", "This, has a comma inside it"]

否则,只需确保拆分逗号前面有引号字符:

s.split(/(?<="),/) #=> ["\"This is a normal string\"", "\"This, has a comma inside it\""]

我仍然更喜欢第一种方法,因为它也删除了字符串周围的引号。

最后,如果你有一个带有转义引号的非常棘手的字符串,你可以添加一个检查以查看引号后面是逗号还是字符串的结尾:

s = '"This is a \"normal\" string","This, has a comma inside it"'
s.scan(/"(.*?)"(?:,|\z)/).flatten #=> ["This is a \\\"normal\\\" string", "This, has a comma inside it"]