1

I have to split an input comma separated string and store the result in an array.

Following works great

arr=inputString.split(",")

for this example

 John, Doe       =>arr[0]="John"      arr[1]="Doe" 

But it fail to get following expected output

"John, Doe", Dan  =>arr[0]="John, Doe" arr[1]="Dan"
 John, "Doe, Dan" =>arr[0]="John"      arr[1]="Doe, Dan"

Following regex too didn't help

        var regExpPatternForDoubleQuotes="\"([^\"]*)\"";
        arr=inputString.match(regExpPatternForDoubleQuotes);
        console.log("txt=>"+arr)

The String could contain more than two double-quotes.

I am trying above in JavaScript.

Watt
  • 3,118
  • 14
  • 54
  • 85
  • Thanks for link. Didn't know it was already answered. But the linked answered is very verbose and good one. The answer here is quick and short. I prefer the latter in my case. – Watt May 20 '13 at 20:58

2 Answers2

2

This works:

var re = /[ ,]*"([^"]+)"|([^,]+)/g;
var match;
var str = 'John, "Doe, Dan"';
while (match = re.exec(str)) {
    console.log(match[1] || match[2]);
}

How it works:

/
    [ ,]*     # The regex first skips whitespaces and commas
    "([^"]+)" # Then tries to match a double-quoted string
    |([^,]+)  # Then a non quoted string
/g            # With the "g" flag, re.exec will start matching where it has
              # stopped last time

Try here: http://jsfiddle.net/Q5wvY/1/

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
0

Try to use this pattern with the exec method:

/(?:"[^"]*"|[^,]+)+/g
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125