$input = '7374,726327,"76,237",32324,"21,342,857",23'; print("input: $input\n"); $output = ''; foreach ($input) { if (/\G("[^"]+")/gc) { my $quoted = $1; $quoted =~ s/,//g; $output .= $quoted; redo; } # Unmatched quote. if (/\G"/gc) { $output .= '"'; redo; } if (/\G([^"]+)/gc) { $output .= $1; redo; } } print("output: $output\n");