简体   繁体   中英

Perl regex substitution

I need to match exactly "", but not ,"", for example in this string

"abc","123","def","","asd","876"",345

I need to substitute the "", following the "876" but leave the "" after "def" alone.

The regex I have right now is

$line =~ s/[^,]"",/",/g

However this substitutes the 6 from "876" .

Use a group replacement:

$line =~ s/([^,])"",/$1",/g

Or a lookbehind:

$line =~ s/(?<!,)"",/",/g

Having said that, "" is a CSV quoted quote, it can appear inside a string. For example, this is valid: """abc""" . To avoid breaking that, also exclude " from the lookbehind:

$line =~ s/(?<![,"])"",/",/g

You are trying to fix a broken CSV file. Doing it with a pattern match is not the best solution. You should try fixing it by using Text::CSV_XS module with allow_loose_quotes => 1 option.

This converts the broken col to an empty col and double quotes the last column. Not quite sure if that is what your looking for but there you go.

use strict ;

my $line = '"abc","123","def","","asd","876"",345' ;

$line =~ s/\,{0,1}\"\"\,/\,\"\"\,/g ;
my @foo = split(/\,/,$line) ;
$foo[$#foo] =~ s/^|$/\"/g ;
$line = join ",", @foo ;

print "\n$line\n" ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM