如何解析Ruby中引用的参数列表?
我有以下案文:如何解析Ruby中引用的参数列表?,ruby,Ruby,我有以下案文: text = '"Friend", "One, Two, Three", "something else"' 我想将其转换为数组: array = [ "Friend", "One, Two, Three", "something else" ] 我怎么能用Ruby做呢?简单的split()。也许有一些库可以做到这一点?Ruby的CSV解析器不喜欢“,”中元素之间的空格,但是如果你清除了它,你可以使用它 > s = '"Friend", "One, Tw
text = '"Friend", "One, Two, Three", "something else"'
我想将其转换为数组:
array = [
"Friend",
"One, Two, Three",
"something else"
]
我怎么能用Ruby做呢?简单的
split()。也许有一些库可以做到这一点?Ruby的CSV解析器不喜欢“,”
中元素之间的空格,但是如果你清除了它,你可以使用它
> s = '"Friend", "One, Two, Three", "something else"'
> t = s.gsub(/",\s*"/, '","')
> CSV.parse t
=> [["Friend", "One, Two, Three", "something else"]]
使用正则表达式:
text = '"Friend", "One, Two, Three", "something else"'
text.scan(/\"([,\ \w]+)\"/).flatten
#=> ["Friend", "One, Two, Three", "something else"]
您应该使用scan
text.scan(/"([^"]*)"/).flatten
# => ["Friend", "One, Two, Three", "something else"]
或
或者,您可以使用split
text[1...-1].split(/", "/)
# => ["Friend", "One, Two, Three", "something else"]
也许CSV解析器可以做到这一点?
text[1...-1].split(/", "/)
# => ["Friend", "One, Two, Three", "something else"]