【发布时间】:2010-10-12 15:03:24
【问题描述】:
我在解析带引号的 CSV 数据时遇到了一些问题。我的主要问题是字段中的引号。在以下示例中,第 1 - 4 行正常工作,但第 5,6 和 7 行不正常。
COLLOQ_TYPE,COLLOQ_NAME,COLLOQ_CODE,XDATA
S,"BELT,FAN",003541547,
S,"BELT V,FAN",000324244,
S,SHROUD SPRING SCREW,000868265,
S,"D" REL VALVE ASSY,000771881,
S,"YBELT,"V"",000323030,
S,"YBELT,'V'",000322933,
我想避免 Text::CSV,因为它没有安装在目标服务器上。意识到 CSV 比看起来更复杂,我正在使用 Perl Cookbook 中的食谱。
sub parse_csv {
my $text = shift; #record containg CSVs
my @columns = ();
push(@columns ,$+) while $text =~ m{
# The first part groups the phrase inside quotes
"([^\"\\]*(?:\\.[^\"\\]*)*)",?
| ([^,]+),?
| ,
}gx;
push(@columns ,undef) if substr($text, -1,1) eq ',';
return @columns ; # list of vars that was comma separated.
}
有没有人建议改进正则表达式来处理上述情况?
【问题讨论】:
-
第 5、6 和 7 行不是无效的 CSV 文件吗?