如何基于逗号拆分字符串,而不是基于双引号中的逗号
How to split a string based on comma, but not based on comma in double quote
我想根据逗号拆分这个字符串,而不是根据双引号中的逗号 "
:
my $str = '1,2,3,"4,5,6"';
.say for $str.split(/','/) # Or use comb?
输出应该是:
1
2
3
"4,5,6"
这可能有帮助:
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+/);
}
}
输出:
1
2
3
"4,5,6"
7
8
使用 comb
的快速解决方案,采取除 "
和 ,
之外的任何方法
或带引号的字符串
my $str = '1,2,3,"4,5,6",7,8';
.say for $str.comb: / <-[",]>+ | <["]> ~ <["]> <-["]>+ / ;
正如@melpomene 建议的那样,使用 Text::CSV 模块也可以。
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;
}
哪个输出:
123
456
78,91
abc
de,f
ikm
我想根据逗号拆分这个字符串,而不是根据双引号中的逗号 "
:
my $str = '1,2,3,"4,5,6"';
.say for $str.split(/','/) # Or use comb?
输出应该是:
1
2
3
"4,5,6"
这可能有帮助:
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+/);
}
}
输出:
1
2
3
"4,5,6"
7
8
使用 comb
的快速解决方案,采取除 "
和 ,
之外的任何方法
或带引号的字符串
my $str = '1,2,3,"4,5,6",7,8';
.say for $str.comb: / <-[",]>+ | <["]> ~ <["]> <-["]>+ / ;
正如@melpomene 建议的那样,使用 Text::CSV 模块也可以。
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;
}
哪个输出:
123
456
78,91
abc
de,f
ikm