Home > Enterprise >  Regex split on comma that isn't preceded by a specific word
Regex split on comma that isn't preceded by a specific word

Time:10-01

I have a CSV string that I want to split on commas, but only if the comma isn't preceded by a specific word somewhere else before it in the string.

Below is an example of the input.

1,2,3,Test Message,JSON={ "book": { "title": "Hello, there, world" } }

In the above case, any commas after the word 'JSON=' should not cause the string to split, so I would be hoping for the following split.

1
2
3
Test Message
JSON={ "book": { "title": "Hello, there, world" } }

Ideally, I'd like to use Regex.Split to split the string and I think I need to use a negative look behind, but I'm not sure of the syntax required to achieve this.

Any help would be greatly appreciated.

CodePudding user response:

You can use below regex to parse JSON in CSV mentioned here

C# code -

var csvContent = "1,2,3,Test Message,JSON={ \"book\": { \"title\": \"Hello, there, world\" } }";
var split = Regex.Split(csvContent, ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");

JS demo -

const csv = '1,2,3,Test Message,JSON={ "book": { "title": "Hello, there, world" } }';

console.log(csv.split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/));

  • Related