Strongly advise to parse CSV with a tested CSV-parser library instead of any regex.
CSV-parsers for JavaScript
Among the common ones example:
Example usages
Your example using
- .. Papa Parse, can auto-detect the delimiter and has already a default for quoted-strings:
quoteChar: '"'
(like yours). Try it online:
var csvInput = 'a,"d,e,f",g';
var results = Papa.parse(csvString);
console.log(results);
Output (copied from console):
{
data: [
"a",
"d,e,f",
"g"
],
errors: []
meta: {delimiter: ",", linebreak: "↵", aborted: false, truncated: false, cursor: 11}
}
var input = 'a,"d,e,f",g';
var result = $.csv.toArray(input);
console.log(result);
// even configurable
$.csv.toArrays(input, {
delimiter: "\"", // already the default, custom value delimiter character
separator: ',', // already the default, custom field separator character
});
Output:
[
"a",
"d,e,f",
"g"
]
Disadvantage of regular-expressions for CSV parsing
The regex for CSV-parsing can be either simple like split(',')
or long, cumbersome and fragile - catasrophic backracking like described on regular-expressions.info: "A Real Example: Matching CSV Records".
Furthermore:
- a regex is not easy to configure.
- a regex is hard to document, maintain, modularize or extend.
If you still want to try, read
Related questions