Split on comma, but only when not in parenthesis

后端 未结 6 1246
被撕碎了的回忆
被撕碎了的回忆 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:17

    use Text::Balanced qw(extract_bracketed);
    my $string = "ab,12,20100401,xyz(A,B(a,d))";
    my @params = ();
    while ($string) {
        if ($string =~ /^([^(]*?),/) {
            push @params, $1;
            $string =~ s/^\Q$1\E\s*,?\s*//;
        } else {
            my ($ext, $pre);
            ($ext, $string, $pre) = extract_bracketed($string,'()','[^()]+');
            push @params, "$pre$ext";
            $string =~ s/^\s*,\s*//;
        }
    }
    

    This one supports:

    • nested parentheses;
    • empty fields;
    • strings of any length.

提交回复
热议问题