s1 ='a,b,c,"x,y,z" '
m1 = s1.split(',')
"x,y,z"
不应该用逗号分隔
预期结果应为['a','b','c',“x,y,z”],总大小为4
我怎么能在Ruby中做到这一点
答案 0 :(得分:3)
使用csv
模块:
irb(main):001:0> require 'csv'
=> true
irb(main):002:0> CSV.parse_line('a,b,c,"x,y,z"')
=> ["a", "b", "c", "x,y,z"]
答案 1 :(得分:1)
试试这个:
s1 ='a,b,c,"x,y,z" '
quotes = s1.match(/".+"/)
s1.split(/,(?![#{quotes}])|,(?=")/)
答案 2 :(得分:0)
可能吗?可能吗?我是否终于有机会使用Ruby的奇异边界flip-flop operator?
让我们试试:
str ='a,b,c,"x,y,z",d,e,"1,2,3",f '
u = ''
str.split(?,).each_with_object([]) do |s,a|
t = s.strip
if (t[0]==?") .. (t[-1]==?")
u = '' if t[0]==?"
u << t
if t[-1]==?"
a << u
else
u << ?,
end
else
a << t
end
end
#=> ["a", "b", "c", "\"x,y,z\"", "d", "e", "\"1,2,3\"", "f"]
答案 3 :(得分:0)
你可以像这样做一个单词def,用逗号分隔字符串,除非逗号在简单的OR双引号内
def to_structure(lst, stru):
lst = iter(lst)
for elem in stru:
if isinstance(elem, list):
yield list(to_structure(lst, elem))
else:
yield next(lst, None) # replace missing elements with None
# alternately, raise ValueError (see also pep 479)
# try:
# yield next(lst)
# except StopIteration:
# raise ValueError("Not enough elements")
list(to_structure(range(4), [[0,0],[0],[[0]]])) # -> [[0, 1], [2], [[3]]]
list(to_structure(range(3), [[0,0],[0],[[0]]])) # -> [[0, 1], [2], [[None]]]