Teachme Teachme - 2 months ago 8x
C# Question

Split a string that has white spaces, unless they are enclosed within "quotes"?

To make things simple:

string streamR = sr.ReadLine(); // sr.Readline results in one "two two"

I want to be able to save them as two different strings, remove all spaces EXCEPT for the spaces found between quotation marks. Therefore, what I need is:

string 1 = one
string 2 = two two

So far what I have found that works is the following code, but it removes the spaces within the quotes.

//streamR.ReadLine only has two strings
string[] splitter = streamR.Split(' ');
str1 = splitter[0];
// Only set str2 if the length is >1
str2 = splitter.Length > 1 ? splitter[1] : string.Empty;

The output of this becomes


I have looked into Regular Expression to split on spaces unless in quotes however I can't seem to get regex to work/understand the code, especially how to split them so they are two different strings. All the codes there give me a compiling error (I am using

string input = "one \"two two\" three \"four four\" five six";
var parts = Regex.Matches(input, @"[\""].+?[\""]|[^ ]+")
                .Select(m => m.Value)