@ojlovecd使用正則表達式有一個很好的答案。
但是,他的答案過於複雜,所以這裏是我的類似,更簡單的答案。
public string[] StringToArray(string input) {
var pattern = new Regex(@"
\[
(?:
\s*
(?<results>(?:
(?(open) [^\[\]]+ | [^\[\],]+ )
|(?<open>\[)
|(?<-open>\])
)+)
(?(open)(?!))
,?
)*
\]
", RegexOptions.IgnorePatternWhitespace);
// Find the first match:
var result = pattern.Match(input);
if (result.Success) {
// Extract the captured values:
var captures = result.Groups["results"].Captures.Cast<Capture>().Select(c => c.Value).ToArray();
return captures;
}
// Not a match
return null;
}
使用此代碼,你會看到StringToArray("[a, b, [c, [d, e]], f, [g, h], i]")
將返回以下陣列:["a", "b", "[c, [d, e]]", "f", "[g, h]", "i"]
。
有關用於匹配平衡牙套的平衡組的更多信息,請參閱Microsoft's documentation。
更新:
按照意見,如果你也想平衡引號,這裏是一個可能的修改。 (請注意,在C#中的"
轉義爲""
)我還添加了圖案的描述,以幫助澄清:
var pattern = new Regex(@"
\[
(?:
\s*
(?<results>(?: # Capture everything into 'results'
(?(open) # If 'open' Then
[^\[\]]+ # Capture everything but brackets
| # Else (not open):
(?: # Capture either:
[^\[\],'""]+ # Unimportant characters
| # Or
['""][^'""]*?['""] # Anything between quotes
)
) # End If
|(?<open>\[) # Open bracket
|(?<-open>\]) # Close bracket
)+)
(?(open)(?!)) # Fail while there's an unbalanced 'open'
,?
)*
\]
", RegexOptions.IgnorePatternWhitespace);
+1一個具有挑戰性的問題。不過,我認爲這通常是codereview:codereview.stackexchange.com/faq#questions。 –