Split on comma, but only when not in parenthesis

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

    Well, old question, but I just happened to wrestle with this all night, and the question was never marked answered, so in case anyone arrives here by Google as I did, here's what I finally got. It's a very short answer using only built-in PERL regex features:

    my $string='ab,12,20100401,xyz(A,B)';
    string =~ 's/((\((?>[^)(]*(?2)?)*\))|[^,()]*)(*SKIP)([,])/$1\n/g';
    my @array=split('\n',$string);
    

    Commas that are not inside parentheses are changed to newlines and then the array is split on them. This will ignore commas inside any level of nested parentheses, as long as they're properly balanced with a matching number of open and close parens.

    This assumes you won't have newline \n characters in the initial value of $string. If you need to, either temporarily replace them with something else before the substitution line and then use a loop to replace back after the split, or just pick a different delimiter to split the array on.

提交回复
热议问题