Split string by comma but want to keep empty fields too

时间:2017-10-19 12:43:21

标签: javascript jquery regex

I am trying to read csv file.I split the file by line break now i am trying to split each line by commas ",". below regex working fine for me but the problem is it omits the empty fields.

I want this output

[Type,Name,Description,"",Comments]

But getting 4 index rather 5

[Type,Name,Description,Comments]

str = "Type,Name,Description,,Comments"
var arr = str.match(/("[^"]*")|[^,]+/g);

/("[^"]*")|[^,]+/g)

above regex is used to avoid this problem if comma appears in double quotes Type,Name,"Description,s",,Comments

I am new to regex and don't know much how can i achieve it. Thanks in advance

2 个答案:

答案 0 :(得分:1)

只需使用String#split功能并将,传递给它。



var str = "Type,Name,Description,,Comments"
var arr = str.split(',');

console.log(arr);




答案 1 :(得分:1)

您可以为空部件#!/bin/bash # Create a batch file to reinstall using setup-{ARCH}.exe # all packages reported as incomplete print_error=1 if [ $# -eq 1 ] then if [ $1 == "-I" ] then lista=$(mktemp) cygcheck -c | grep "Incomplete" > $lista print_error=0 fi if [ $1 == "-A" ] then lista=$(mktemp) cygcheck -cd | sed -e "1,2d" > $lista print_error=0 fi fi if [ $# -eq 2 ] then if [ $1 == "-f" ] then lista=$2 print_error=0 fi fi # error message if options are incorrect. if [ $print_error -eq 1 ] then echo -n "Usage : " $(basename $0) echo " [ -A | -I | -f filelist ]" echo " create cyg-reinstall-{ARC}.bat from" echo " options" echo " -A : All packages as reported by cygcheck" echo " -I : incomplete packages as reported by cygcheck" echo " -f : packages in filelist (one per raw)" exit 1 fi if [ $(arch) == "x86_64" ] then A="x86_64" else A="x86" fi # writing header echo -n -e "setup-${A}.exe " > cyg-reinstall-${A}.bat # option -x remove and -P install # for re-install packages we need both if [ $1 == "-I" ] then awk 'BEGIN{printf(" -x ")} NR==1{printf $1}{printf ",%s", $1}' ${lista} >> cyg-reinstall-${A}.bat fi awk 'BEGIN{printf(" -P ")} NR==1{printf $1}{printf ",%s", $1} END { printf "\r\n pause "}' ${lista} >> cyg-reinstall-${A}.bat # execution permission for the script chmod +x cyg-reinstall-${A}.bat 添加图案。

(?=,(,|$))