You can even do that without Regex: a LINQ expression with String.Split
can do the job.
You can split your string before by "
then split only the elements with even index in the resulting array by
.
var result = myString.Split('"')
.Select((element, index) => index % 2 == 0 // If even index
? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) // Split the item
: new string[] { element }) // Keep the entire item
.SelectMany(element => element).ToList();
For the string:
This is a test for "Splitting a string" that has white spaces, unless they are "enclosed within quotes"
It gives the result:
This
is
a
test
for
Splitting a string
that
has
white
spaces,
unless
they
are
enclosed within quotes
UPDATE
string myString = "WordOne \"Word Two\"";
var result = myString.Split('"')
.Select((element, index) => index % 2 == 0 // If even index
? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) // Split the item
: new string[] { element }) // Keep the entire item
.SelectMany(element => element).ToList();
Console.WriteLine(result[0]);
Console.WriteLine(result[1]);
Console.ReadKey();
UPDATE 2
How do you define a quoted portion of the string?
We will assume that the string before the first "
is non-quoted.
Then, the string placed between the first "
and before the second "
is quoted. The string between the second "
and the third "
is non-quoted. The string between the third and the fourth is quoted, ...
The general rule is: Each string between the (2*n-1)th (odd number) "
and (2*n)th (even number) "
is quoted. (1)
What is the relation with String.Split
?
String.Split with the default StringSplitOption (define as StringSplitOption.None) creates an list of 1 string and then add a new string in the list for each splitting character found.
So, before the first "
, the string is at index 0 in the splitted array, between the first and second "
, the string is at index 1 in the array, between the third and fourth, index 2, ...
The general rule is: The string between the nth and (n+1)th "
is at index n in the array. (2)
The given (1)
and (2)
, we can conclude that: Quoted portion are at odd index in the splitted array.