我在解析带有引号的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.
}
有没有人能提出改进正则表达式以处理上述情况的建议?