如何在Ruby中拆分CSV字符串? [英] How do I split apart a CSV string in Ruby?

查看:79
本文介绍了如何在Ruby中拆分CSV字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以CSV文件中的这一行为例:

I have this line as an example from a CSV file:

2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes",,,1,0,"endofline"

我想将其拆分为一个数组。立即想到的只是拆分逗号,但是其中一些字符串中包含逗号,例如生命和生命过程,生命过程,它们应该作为单个元素保留在数组中。还请注意,有两个逗号之间没有任何逗号-我想将它们作为空字符串获取。

I want to split it into an array. The immediate thought is to just split on commas, but some of the strings have commas in them, eg "Life and Living Processes, Life Processes", and these should stay as single elements in the array. Note also that there's two commas with nothing in between - i want to get these as empty strings.

换句话说,我想要获取的数组是

In other words, the array i want to get is

[2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes","","",1,0,"endofline"]

我能想到涉及eval的骇客方式,但我希望有人能拿出一个干净的正则表达式来做到这一点...

I can think of hacky ways involving eval but i'm hoping someone can come up with a clean regex to do it...

干杯,最多

推荐答案

str=<<EOF
2412,21,"Which of the following is not found in all cells?","Curriculum","Life and Living Processes, Life Processes",,,1,0,"endofline"
EOF
require 'csv' # built in

p CSV.parse(str)
# That's it! However, empty fields appear as nil.
# Makes sense to me, but if you insist on empty strings then do something like:
parser = CSV.new(str)
parser.convert{|field| field.nil? ? "" : field}
p parser.readlines

这篇关于如何在Ruby中拆分CSV字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆