首页 > 解决方案 > split string (based on comma) into array adds an empty item at the end of list

问题描述

I'm using below regex to split a string in the basis of comma into array, which works completely fine.

my $string = '$n(bar,foo),  (bar),a.*$n(f04((?!z).)*)b, 
 hello$n(((((((abcdef)))))))world';

my @array;
push @array, $1 while $string =~ /
            ((?:
              [^(),]+ |
              ( \(
                (?: [^()]+ | (?2) )*
              \) )
            )*)
            (?: ,\s* | $)
            /xg;


$VAR1 = [
          '$n(bar,foo)',
          '(bar)',
          'a.*$n(f04((?!z).)*)b',
          'hello$n(((((((abcdef)))))))world',
          ''
];

Problem is it always adds an empty string as the last item of an array. I don't want this. Please help.

标签: arraysregexperlsplit

解决方案


Your first capturing group contains a *-quantified non-capturing group, and thus can be empty. To avoid that, you need to use a + quantifier to make it match at least once.

push @array, $1 while $string =~ /
        ((?:
          [^(),]+ |
          ( \(
            (?: [^()]+ | (?2) )*
          \) )
        )+)           # < HERE
        (?: ,\s* | $)
        /xg;

推荐阅读