csv 中有引号,引号内还有逗号

【问题】

I am trying to parse a comma separated string using:

val array = input.split(",")

Then I notice that some input lines have "," inside a quotation mark:

data0, "data1", data2, data3, "data4-1, data4-2, data4-3", data5

*Note that the data is not very clean, so some fields are inside quotation marks while some don't


How do I split such line into:

array(0) = data0
array(1) = data1
array(2) = data2
array(3) = data3
array(4) = data4-1, data4-2, data4-3
array(5) = data5

【回答】

这个问题的麻烦之处在于:引号里的逗号不应当被识别为分隔符,而引号外的逗号才是分隔符。JAVA当然没问题,但代码有些复杂。如无特殊要求可以用SPL再嵌入到JAVA中,只需一句代码:


A

1

=file("d:\\souce.txt").import@qc()

 

A: 函数f.import@c()将文本文件souce.txt按逗号分隔符读为二维表,并自动做trim选项@q表示自动脱去引号。结果如下:

undefined

 

如果字符串并非来自文件,而是个变量str,则需要将A1代码改成=str.import@qc()

用下面字符串做测试:

data0, "data1", data2, data3, "data4-1, data4-2, data4-3", data5

"data0, data0", data1, "data2", data3-1, "data4-2", data5

结果如下:

undefined

 

上述代码很容易和JAVA集成,参考Java 如何调用 SPL 脚本