分隔包含逗号和双引号的csv文件的最佳方法是什么?

时间:2014-06-28 01:36:47

标签: ruby regex

假设我有以下字符串,我想要以下输出而不需要csv。

this, "what I need", to, do, "i, want, this", to, work

this
what i need
to
do
i, want, this
to
work

1 个答案:

答案 0 :(得分:4)

此问题是此问题中向"regex-match a pattern, excluding..."

解释的技术的典型案例

我们可以通过一个非常简单的正则表达式解决它:

"([^"]+)"|[^, ]+

交替|的左侧匹配完整的“引号”并将内容捕获到Group1。右侧匹配既不是逗号也不是空格的字符,我们知道它们是正确的,因为它们与左侧的表达式不匹配。

选项2:允许多个字

在您的输入中,所有令牌都是单个字词,但如果您还希望正则表达式适用于my cat scratches, "what I need", your dog barks,请使用此字符:

"([^"]+)"|[^, ]+(?:[ ]*[^, ]+)*

唯一的区别是添加(?:[ ]*[^, ]+)*,可选择添加空格+字符,零次或多次。

此程序显示了如何使用正则表达式(请参阅online demo底部的结果):

subject = 'this, "what I need", to, do, "i, want, this", to, work'
regex = /"([^"]+)"|[^, ]+/
# put Group 1 captures in an array
mymatches = []
subject.scan(regex) {|m|
     $1.nil? ? mymatches << $& : mymatches << $1
}
mymatches.each { |x| puts x }

<强>输出

this
what I need
to
do
i, want, this
to
work

参考