我有一个看起来像这样的记录集
"BOSW0001","Mr","Wayne","Boswell","Wayne,Jessica & Lyn","31 Baker St"
"ELLI0007","Mrs","Bronwyn","Elliott","Bronwyn, Paul & Arianne","98A Dandaraga Rd"
"KENN0001","Mr","Leigh","Kenning","Leigh & Beth,Cole","22 Lake St"
Run Code Online (Sandbox Code Playgroud)
我想,用pipe(|)替换逗号()而不替换里面的逗号
"Leigh & Bethie,Coles"
"Waynez,Jessy & Lyne"
"Bronwynie, Paula & Arianne"
Run Code Online (Sandbox Code Playgroud)
如何使用正则表达式或其他方法执行此操作?
fri*_*edo 12
你不是用正则表达式做的; 你用一个合适的CSV解析器来做到这一点.这是一个使用Text :: CSV_XS的(未经测试的)示例- 这是商业中最好的.
use strict;
use warnings;
use Text::CSV_XS;
my $in_file = "whatever.csv";
my $out_file = "new.dat";
open my $fh, '<', $in_file or die "$in_file: $!";
open my $out_fh, '>', $out_file or die "$out_file: $!";
my $in_csv = Text::CSV_XS->new;
my $out_csv = Text::CSV_XS->new( { sep_char => '|', eol => "\n" } );
while( my $row = $in_csv->getline( $fh ) ) {
$out_csv->print( $out_fh, $row );
}
Run Code Online (Sandbox Code Playgroud)
仅仅为了TIMTOWTDI,这里有一个使用核心模块Text :: ParseWords的例子.
#!/usr/bin/env perl
use strict;
use warnings;
use Text::ParseWords 'parse_line';
foreach my $line (<DATA>) {
print join '|', parse_line(',', 1, $line);
}
__DATA__
"BOSW0001","Mr","Wayne","Boswell","Wayne,Jessica & Lyn","31 Baker St"
"ELLI0007","Mrs","Bronwyn","Elliott","Bronwyn, Paul & Arianne","98A Dandaraga Rd"
"KENN0001","Mr","Leigh","Kenning","Leigh & Beth,Cole","22 Lake St"
Run Code Online (Sandbox Code Playgroud)