正規表現なしでそれを行うこともできます。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番目の文字列の前に配置された文字列"
が引用されます。"
2番目と3番目の間の文字列は"
引用符で囲まれていません。3番目と4番目の間の文字列は引用符で囲まれています...
一般的な規則は次のとおりです。(2 * n-1)番目(奇数)"
と(2 * n)番目(偶数)の間の各文字列"
は引用符で囲まれます。(1)
との関係は何String.Split
ですか?
String.SplitとデフォルトのStringSplitOption(StringSplitOption.Noneとして定義)は、1つの文字列のリストを作成し、見つかった分割文字ごとにリストに新しい文字列を追加します。
したがって、最初のの前に"
、文字列は分割された配列のインデックス0にあり、1番目と2番目の間にあり"
、文字列は配列のインデックス1にあり、3番目と4番目のインデックス2の間にあります。
一般的な規則は次のとおりです。n番目と(n + 1)番目の間の文字列は"
、配列のインデックスnにあります。(2)
与えられた(1)
と(2)
、次のように結論付けることができます。引用符で囲まれた部分は分割された配列の奇数インデックスにあります。