@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。
更新:
根据 cmets,如果您还想平衡报价,这里有一个可能的修改。 (请注意,在 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);