Split by comma if that comma is not located between two double quotes

c#, regex

Solution

It'll be much easier to do this with `Matches` than with `Split`, for example

string[] asYouWanted = Regex.Matches(input, @"[A-Za-z0-9]+:"".*?""")
    .Cast<Match>()
    .Select(m => m.Value)
    .ToArray();

although if there is any chance of your values (or fields!) containing escaped quotes (or anything similarly tricky), then you might be better off with a proper CSV parser.

If you do have escaped quotes in your values, I think the following regex the work - give it a test:

@"field3:""value3\\"",value4""", @"[A-Za-z0-9]+:"".*?(?<=(?<!\\)(\\\\)*)"""

The added `(?<=(?<!\\)(\\\\)*)` is supposed to make sure that the `"` it stops matching on is preceeded by only an even number of slashes, as an odd number of slashes means it is escaped.

Problem

I am looking to split such string by comma : ``` field1:"value1", field2:"value2", field3:"value3,value4" ``` into a `string[]` that would look like: ``` 0 field1:"value1" 1 field2:"value2" 2 field3:"value3,value4" ``` I am trying to do that with `Regex.Split` but can't seem to work out the regular expression.

Original source