Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

raku

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"
like image 467
chenyf Avatar asked Sep 17 '18 04:09

chenyf


People also ask

How do you separate a string split by a comma?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

How do you split a string with double quotes?

Use method String. split() It returns an array of String, splitted by the character you specified.

How do you handle double quotes and commas in a CSV file?

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.


2 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: / <-[",]>+ | <["]> ~ <["]>  <-["]>+ / ;
like image 117
wamba Avatar answered Sep 22 '22 01:09

wamba


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
like image 45
chenyf Avatar answered Sep 25 '22 01:09

chenyf