如何将逗号分隔的字符串解析为二维数组

时间:2017-11-15 14:40:14

标签: javascript jquery

我想将逗号分隔的字符串解析为二维数组。 这些值用逗号分隔,每个新行用换行符。

$A$1,$B$1,$C$1,$D$1,$E$1,$F$1,$G$1 $A$2,"$B,$2",$C$2,$D$2,$E$2,$F$2,$G$2 $A$3,$B$3,,,,, $A$4,$B$hg4,$C$4,$D$4,$E$4,$F$4,$G$4 $A$5,$B$5,$C$5,$D$5,$E$5,$F$5,$G$5 $A$6,$B$6,$C$6,$D$6,$E$6,$F$6,$G$6 $A$7,$B$7,$C$7,,$E$7,$F$7,$G$7 $A$8,$B$8,$C$8,,$E$8,$F$8,$G$8 $A$9,$B$9,$C$9,,$E$9,$F$9,$G$9 $A$10,$B$10,$C$10,,$E$10,$F$10,$G$10 $A$11,$B$11,$C$11,,$E$11,$F$11,$G$11 $A$12,$B$12,$C$12,$D$12,$E$12,$F$12,$G$12 $A$13,,$C$13,$D$13,$E$13,$F$13,$G$13 ,,$C$14,$D$14,$E$14,$F$14,$G$14 ,,$C$15,$D$15,$E$15,$F$15,$G$15 $A$16,$B$16,$C$16,$D$16,$E$16,$F$16,$G$16 

期望的结果应该是这样的:

arr = [[$A$1],[$B$1],[$C$1],[$D$1],[$E$1],[$F$1],[$G$1]],[[$A$2],["$B,$2"],[$C$2],[$D$2],[$E$2],[$F$2],[$G$2]],[[$A$3],[$B$3],[],[],[],[],[]],[[$A$4],[$B$4],[$C$4],[$D$4],[$E$4],[$F$4],[$G$4]],...

1 个答案:

答案 0 :(得分:0)

您可以按新行拆分,然后使用this answer中的保留引号正则表达式进行拆分。

稍后映射数组中的项目。瞧!

var string = '$A$1,$B$1,$C$1,$D$1,$E$1,$F$1,$G$1\n$A$2,"$B,$2",$C$2,$D$2,$E$2,$F$2,$G$2\n$A$3,$B$3,,,,,\n$A$4,$B$4,$C$4,$D$4,$E$4,$F$4,$G$4',
    result = string.split('\n').map(s => s.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/).map(s => [s]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }