Escape character in C # Split ()

I am parsing some separator separator values, where ? indicated as an escape character if the delimiter is displayed as part of one of the values.

For example: if : is a separator, and in some field the value is 19:30 , this should be written as 19?:30 .

I am currently using string[] values = input.Split(':'); to get an array of all values, but after learning this escape character this will no longer work.

Is there a way to get Split to take escape characters? I checked overload methods and there seems to be no such option directly.

+7
string split c # escaping
source share
3 answers
 string[] substrings = Regex.Split("aa:bb:00?:99:zz", @"(?<!\?):"); 

for

 aa bb 00?:99 zz 

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

(This requires using the System.Text.RegularExpressions namespace.)

+9
source share

This kind of thing is always interesting for code without using Regex.

The following does the trick with one single caveat: the escape character always escapes, it does not have logic to check only valid: ?; . So, the line one?two;three??;four?;five will be split into onewo , three? , fourfive .

  public static IEnumerable<string> Split(this string text, char separator, char escapeCharacter, bool removeEmptyEntries) { string buffer = string.Empty; bool escape = false; foreach (var c in text) { if (!escape && c == separator) { if (!removeEmptyEntries || buffer.Length > 0) { yield return buffer; } buffer = string.Empty; } else { if (c == escapeCharacter) { escape = !escape; if (!escape) { buffer = string.Concat(buffer, c); } } else { if (!escape) { buffer = string.Concat(buffer, c); } escape = false; } } } if (buffer.Length != 0) { yield return buffer; } } 
0
source share

No, there is no way to do this. You will need to use a regular expression (which depends on how exactly you want your "escape character" to behave). In the worst case, I suppose you will need to manually parse.

-one
source share

All Articles