使用Ruby拆分CSV样式的字符串 [英] Split a CSV-style string with Ruby
问题描述
我有来自已加载到内存中的CSV文件的数据。所以我可能有这样的:
I have data from a CSV file that's already loaded into memory. So I might have something like this:
csv_string = 'Value 1,Value 2,"Hey, it\'s value 3!",Value 4 has "some quotes"'
显然我不想做 csv_string.split(,)
。因为它似乎拆分一个CSV风格的字符串这种方式可能是一个不是所有的罕见的需要,我想知道是否有一个解决方案已经在那里。
Obviously I won't want to do csv_string.split(",")
. Since it seems like splitting a CSV-style string this way might be a not-all-that-uncommon need, I was wondering if there's a solution already out there.
推荐答案
对于解析CSV,Ruby附带了 csv
图书馆:
For parsing CSV, Ruby comes with the csv
library:
require 'csv'
CSV.parse(csv_string)
# => [['Value 1', 'Value 2', "Hey, it's value 3!", 'Value 4 has "some quotes"']]
不幸的是,您的字符串实际上并不包含有效的CSV,因此您会真正获得的是以下异常:
Unfortunately, your string doesn't actually contain valid CSV, so what you'll really get is the following exception:
# CSV::MalformedCSVError: Illegal quoting on line 1.
由于你的数据实际上不符合任何通用标准,显然不能有一个通用的解析器,你必须自己编写。
Since your data doesn't actually conform to any common standard, there can obviously not be a common parser and you'll have to write your own.
或者,您可以将数据更改为有效的CSV,例如:
Alternatively, you could change your data to be valid CSV, for example like this:
c = %q[Value 1,Value 2,"Hey, it's value 3!","Value 4 has ""some quotes"""]
CSV.parse(c)
# => [['Value 1', 'Value 2', "Hey, it's value 3!", 'Value 4 has "some quotes"']]
这篇关于使用Ruby拆分CSV样式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!