0

我正在解析以下 CSV 行。我需要拯救"Malformed"如下所示的畸形线条。我可以使用什么正则表达式来做到这一点?我需要考虑什么?

body = %(
"Sensitive",2416,159,"Test "Malformed" Failure",2789,111,7-24-11,1800,0600,"R2","12323","",""
"Sensitive",2742,107,"Test",2791,112,7-24-11,1800,0600,"R1","","",""
"Sensitive",2700,135,"Test",2792,113,7-24-11,1800,0600,"R1","12110","","")

rows = []
body.each_line do |line|
  begin
    rows << FasterCSV.parse_line(line)
  rescue FasterCSV::MalformedCSVError => e
    rows << line if rescue_from_malformed_line(line)
  rescue => e
    Rails.logger.error(e.to_s)
    Rails.logger.info(line)
  end
end
4

2 回答 2

2

我不确定您的数据格式有多畸形,但这是该行的一种方法。

> puts line
"Sensitive",2416,159,"Test "Malformed" Failure",2789,111,7-24-11,1800,0600,"R2","12323","",""
>
> puts line.scan /[\d.-]+|(?:"[^"]*"[^",]*)+/
"Sensitive"
2416
159
"Test "Malformed" Failure"
2789
111
7-24-11
1800
0600
"R2"
"12323"
""
""

注意:在 ruby​​ 1.9.2p290 上测试

于 2011-08-23T01:42:41.240 回答
0

在将嵌套的双引号传递给解析器之前,您可以使用正则表达式将嵌套的双引号替换为单引号。

就像是

.gsub(/(?<!^|,)"(?!,|$)/,"'")
于 2013-01-30T18:14:56.473 回答