你甚至可以在没有 Regex 的情况下做到这一点:一个 LINQ 表达式String.Split可以完成这项工作。
您可以在之前拆分字符串,"然后仅将结果数组中索引为偶数的元素拆分为 .
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();
对于字符串:
This is a test for "Splitting a string" that has white spaces, unless they are "enclosed within quotes"
它给出了结果:
This
is
a
test
for
Splitting a string
that
has
white
spaces,
unless
they
are
enclosed within quotes
更新
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();
更新 2
你如何定义字符串的引号部分?
我们将假设第一个字符串之前的字符串"没有被引用。
然后,放在第一个"和第二个之前的字符串"被引用。第二个"和第三个之间的字符串"不加引号。第三个和第四个之间的字符串被引用,...
一般规则是:第 (2*n-1) 个(奇数)"和第 (2*n) 个(偶数)之间的每个字符串"都被引用。(1)
有什么关系String.Split?
String.Split 使用默认的 StringSplitOption(定义为 StringSplitOption.None)创建一个包含 1 个字符串的列表,然后在列表中为找到的每个拆分字符添加一个新字符串。
因此,在 first 之前",字符串位于拆分数组中的索引 0 处,介于 first 和 second 之间",字符串位于数组中的索引 1 处,位于第三个和第四个之间,索引 2,...
一般规则是:第 n 个和第 (n+1) 个之间的字符串位于"数组中的索引 n 处。(2)
给定(1)and (2),我们可以得出结论: 引用部分在拆分数组中的奇数索引处。