Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

split

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)

like image 781
Teachme Avatar asked Feb 01 '13 21:02

Teachme


People also ask

How do you split a string in white space?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

Can you have a string with a quote inside it?

To place quotation marks in a string in your code In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark.

How do I split a string into multiple spaces?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.

How do you escape quotation marks in a string?

You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.


1 Answers

string input = "one \"two two\" three \"four four\" five six"; var parts = Regex.Matches(input, @"[\""].+?[\""]|[^ ]+")                 .Cast<Match>()                 .Select(m => m.Value)                 .ToList(); 
like image 196
I4V Avatar answered Sep 27 '22 23:09

I4V