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"
To split a string with comma, use the split() method in Java. str. split("[,]", 0);
Use method String. split() It returns an array of String, splitted by the character you specified.
Since CSV files use the comma character "," to separate columns, values that contain commas must be handled as a special case. These fields are wrapped within double quotation marks. The first double quote signifies the beginning of the column data, and the last double quote marks the end.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With