Search code examples
c#stringsplitescaping

Escape character in C#'s Split()


I am parsing some delimiter separated values, where ? is specified as the escape character in case the delimiter appears as part of one of the values.

For instance: if : is the delimiter, and a certain field the value 19:30, this needs to be written as 19?:30.

Currently, I use string[] values = input.Split(':'); in order to get an array of all values, but after learning about this escape character, this won't work anymore.

Is there a way to make Split take escape characters into account? I have checked the overload methods, and there does not seem to be such an option directly.


Solution

  • string[] substrings = Regex.Split("aa:bb:00?:99:zz", @"(?<!\?):");
    

    for

    aa
    bb
    00?:99
    zz
    

    Or as you probably want to unescape ?: at some point, replace the sequence in the input with another token, split and replace back.

    (This requires the System.Text.RegularExpressions namespace to be used.)