Separate a string while storing quoted values ​​(.NET)

I am looking for a way in .NET to break a string, ignoring the delimiters in quotation marks (or another delimiter). (This functionality will match what a regular CSV parser does if the delimiter is a comma.) I'm not sure why this ability is not embedded in String.Split() .

+2
source share
4 answers

You can use a regular expression for this. Example:

 string test = @"this,i""s,a"",test"; string[] parts = Regex.Matches(test, @"(""[^""]*""|[^,])+") .Cast<Match>() .Select(m => m.Value) .ToArray(); foreach (string s in parts) Console.WriteLine(s); 

Conclusion:

 this i"s,a" test 
+5
source

Mark Marc's answer in this post:

The input array is longer than the number of columns in this table. An exception

He mentions a library that you can use for this.

+1
source

Using the @Guffa method, here is my complete solution:

 /// <summary> /// Splits the string while preserving quoted values (ie instances of the delimiter character inside of quotes will not be split apart). /// Trims leading and trailing whitespace from the individual string values. /// Does not include empty values. /// </summary> /// <param name="value">The string to be split.</param> /// <param name="delimiter">The delimiter to use to split the string, eg ',' for CSV.</param> /// <returns>A collection of individual strings parsed from the original value.</returns> public static IEnumerable<string> SplitWhilePreservingQuotedValues(this string value, char delimiter) { Regex csvPreservingQuotedStrings = new Regex(string.Format("(\"[^\"]*\"|[^{0}])+", delimiter)); var values = csvPreservingQuotedStrings.Matches(value) .Cast<Match>() .Select(m => m.Value.Trim()) .Where(v => !string.IsNullOrWhiteSpace(v)); return values; } 
0
source

If you also want to allow a single quote ('), then change the expression to @ "(" "[^" "]" "|' ^ ']' | [^ \ s]) +".

If you want to remove quotes from the string, change your selection to .Select (m => m.Value.Trim (new char [] {'\' ',' ''})).

0
source

Source: https://habr.com/ru/post/1314765/


All Articles