Teachme Teachme - 3 months ago 14
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

one
two


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
System.Text.RegularExpressions
)

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