Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by comma, but ignore commas inside quotes [duplicate]

Example string:

"Foo","Bar, baz","Lorem","Ipsum"

Here we have 4 values in quotes separated by commas.

When I do this:

str.split(',').forEach(…

than that will also split the value "Bar, baz" which I don't want. Is it possible to ignore commas inside quotes with a regular expression?

like image 725
Šime Vidas Avatar asked May 10 '14 14:05

Šime Vidas


Video Answer


1 Answers

One way would be using a Positive Lookahead assertion here.

var str = '"Foo","Bar, baz","Lorem","Ipsum"',
    res = str.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);

console.log(res);  // [ '"Foo"', '"Bar, baz"', '"Lorem"', '"Ipsum"' ]

Regular expression:

,               ','
(?=             look ahead to see if there is:
(?:             group, but do not capture (0 or more times):
(?:             group, but do not capture (2 times):
 [^"]*          any character except: '"' (0 or more times)
 "              '"'
){2}            end of grouping
)*              end of grouping
 [^"]*          any character except: '"' (0 or more times)
$               before an optional \n, and the end of the string
)               end of look-ahead

Or a Negative Lookahead

var str = '"Foo","Bar, baz","Lorem","Ipsum"',
    res = str.split(/,(?![^"]*"(?:(?:[^"]*"){2})*[^"]*$)/);

console.log(res); // [ '"Foo"', '"Bar, baz"', '"Lorem"', '"Ipsum"' ]
like image 128
hwnd Avatar answered Oct 03 '22 00:10

hwnd