我在使用引号解析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,
Run Code Online (Sandbox Code Playgroud)
我想避免使用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.
}
Run Code Online (Sandbox Code Playgroud)
有没有人建议改进正则表达式来处理上述情况?