除非逗号在引号内,否则用逗号将字符串拆分为数组

时间:2015-10-27 21:09:08

标签: ruby

在Ruby中给出一个数组字符串,引号中的一些项目包含逗号:

my_string.inspect
# => "\"hey, you\", 21"

如何获得数组:

["hey, you", " 21"] 

2 个答案:

答案 0 :(得分:6)

Ruby标准CSV库.parse_csv就是这样做的。

require 'csv'
"\"hey, you\", 21".parse_csv
# => ["hey, you", " 21"] 

答案 1 :(得分:2)

是的,使用CSV::parse_line是这里的方法,但您也可以使用正则表达式:

r = /
    (?:     # Begin non-capture group
    (?<=\") # Match a double-quote in a positive lookbehined
    .+?     # Match one or more characters lazily
    (?=\")  # Match a double quote in a positive lookahead.
    )       # End non-capture group
    |       # Or
    \s\d+   # Match a whitespace character followed by one or more digits
    /x      # Extended mode

str = "\"hey, you\", 21"
str.scan(r)
  #=> ["hey, you", " 21"]

如果您希望"21"而不是" 21",请删除\s