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
)
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.
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.
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.
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.
string input = "one \"two two\" three \"four four\" five six"; var parts = Regex.Matches(input, @"[\""].+?[\""]|[^ ]+") .Cast<Match>() .Select(m => m.Value) .ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With