這不是我清楚,如果這個例子代表了這些JSON式的羣體的潛力無限嵌套,或者只是一層嵌套。
如果只有一個級別嵌套是可能的,一個簡單的正則表達式會做:
(請注意,我並沒有一個IDE寫這個,這個概念應該是正確的,但語法錯誤,不能在保證當然,道歉)
string pattern = @"(?<key>)[A-Z]+)\s(?<value>({.+?}|[^{},]+))";
List<string[]> results = new List<string[]>(); //probably not best data structure
MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.SingleLine | RegexOptions.IgnoreCase);
foreach(Match match in matches)
{
if(match.Success)
{
results.Add(new string[] {
match.Groups["key"].Value,
match.Groups["value"].Value
});
}
}
如果他們可以嵌套很多級別,你可能想要遞歸的方式。這將需要拆分值將比賽拖入嵌套的價值和簡單的價值:
string pattern = @"(?<key>)[A-Z]+)\s({(?<nested>.+?)}|(?<simple>[^{},]+))";
和每個地方嵌套有一個值匹配,對這個值執行相同的例行:
void Deserialize(string input, List<string[]> values)
{
MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.SingleLine | RegexOptions.IgnoreCase);
foreach(Match match in matches)
{
if(match.Success)
{
if(match.Groups["nested"].Success && !string.IsNullOrEmpty(match.Groups["nested"].Value))
{
Deserialize(match.Groups["nested"].Value, values);
}
else
{
values.Add(new string[] {
match.Groups["key"].Value,
match.Groups["simple"].Value
});
}
}
}
}
是,遞歸地接近這一是我拍攝的。我將編輯我的帖子,我會嘗試你的榜樣。我從來沒有使用過遞歸正則表達式。 – ademers 2009-11-16 01:23:23
@Alex請參閱我的答案修訂。 – 2009-11-16 01:28:49
先生,您的答案是非常珍貴的!最好的, – BillW 2009-11-16 01:57:56