javascriptstring

Regex - get comma if it does not have an escaped quote at some point in front of it


I'm struggling with a regex expression. I have a string like this:

700,\"some text, and more text\",False,0000000000,text,\"806,474.72\"

And I need to split it into fields by commas, unless the comma is preceded by an escaped quote. The desired output is:

[0] 700
[1] Some text, and more text
[2] False
[3] 0000000000
[4] text
[5] 806,474.72

What would be the right Regex expression for this?

edit: as Barmer pointed out, the criteria should be "unless the comma is between escaped quotes" I'm open to non-regex methods, but I would need some guidance on the string manipulation.


Solution

  • It's possible that I didn't explain the issue correctly, but none of the provided answers accurately split the string or would be able to handle the large amount of data I will eventually be working with without timing out. Here's what did work for my case:

    var str = 'value1,"value2,with,commas",value3';
    var parts = str.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/);