perl - Split on comma, but only when not in parenthesis -
i trying split on string comma delimiter
my $string='ab,12,20100401,xyz(a,b)'; @array=split(',',$string);
if split above array have values
ab 12 20100401 xyz(a, b)
i need values below.
ab 12 20100401 xyz(a,b)
(should not split xyz(a,b) 2 values) how do that?
use text::balanced qw(extract_bracketed); $string = "ab,12,20100401,xyz(a,b(a,d))"; @params = (); while ($string) { if ($string =~ /^([^(]*?),/) { push @params, $1; $string =~ s/^\q$1\e\s*,?\s*//; } else { ($ext, $pre); ($ext, $string, $pre) = extract_bracketed($string,'()','[^()]+'); push @params, "$pre$ext"; $string =~ s/^\s*,\s*//; } }
this 1 supports:
- nested parentheses;
- empty fields;
- strings of length.
Comments
Post a Comment