How to split a string based on comma, but not based on comma in double quote

Viewed 303

I want to split this string based on comma, but not based on the comma in double quote ":

my $str = '1,2,3,"4,5,6"';
.say for $str.split(/','/) # Or use comb?

The output should be:

1
2
3
"4,5,6"
3 Answers

fast solution with comb, take anything but not " nor , or take quoted string

my $str = '1,2,3,"4,5,6",7,8';
.say for $str.comb: / <-[",]>+ | <["]> ~ <["]>  <-["]>+ / ;

as @melpomene suggested, use the Text::CSV module works too.

use Text::CSV;

my $str = '123,456,"78,91",abc,"de,f","ikm"';
for csv(in => csv(in => [$str], sep_char => ",")) -> $arr {
   .say for @$arr;
}

which output:

123
456
78,91
abc
de,f
ikm

This may help:

my $str = ‘1,2,3,"4,5,6",7,8’;

for $str.split(/ \" \d+ % ',' \"/, :v) -> $l {
  if $l.contains('"') {
    say $l.Str;
  } else {
    .say for $l.comb(/\d+/);
  }
}

Output:

1
2
3
"4,5,6"
7
8
Related