Split on comma, but only when not in parenthesis

后端 未结 6 1366
被撕碎了的回忆
被撕碎了的回忆 2021-01-02 23:42

I am trying to do a split on a string with comma delimiter

my $string=\'ab,12,20100401,xyz(A,B)\';
my @array=split(\',\',$string);

If I do

6条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 00:21

    Here is my attempt. It should handle depth well and could even be extended to include other bracketed symbols easily (though harder to be sure that they MATCH). This method will not in general work for quotation marks rather than brackets.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my $string='ab,12,20100401,xyz(A(2,3),B)';
    
    print "$_\n" for parse($string);
    
    sub parse {
      my ($string) = @_;
      my @fields;
    
      my @comma_separated = split(/,/, $string);
    
      my @to_be_joined;
      my $depth = 0;
      foreach my $field (@comma_separated) {
        my @brackets = $field =~ /(\(|\))/g;
        foreach (@brackets) {
          $depth++ if /\(/;
          $depth-- if /\)/;
        }
    
        if ($depth == 0) {
          push @fields, join(",", @to_be_joined, $field);
          @to_be_joined = ();
        } else {
          push @to_be_joined, $field;
        }
      }
    
      return @fields;
    }
    

提交回复
热议问题