2014-09-19 44 views
2

如何在C#中使用正則表達式解析下面的字符串並返回匹配和匹配組集合中的內容?開始標記是[[和]]。任何人都可以幫忙C#正則表達式檢索層次字符串

[[Parent1 [[Child 1]],[[Child 2]],[[Child 3]]]] [[Parent2 [[Child 1]],[[Child 2]]]] 

尋找輸出如下。

item: Parent1 
Children: [Child1, Child2, Child3] 
item: Parent2 
Children: [Child1, Child2] 
+0

您可以像這樣得到'[[Child1]],[[Child2]],[[Child3]]'不像'[Child1,Child2, Child3]' – 2014-09-19 10:50:12

+0

是的。那很好。但是如何?謝謝。 – Paul 2014-09-19 10:51:40

+0

你必須用\ – HimBromBeere 2014-09-19 10:56:37

回答

2

你可以試試下面的正則表達式測試,

(?<=^|]\s)\[\[(\S+)|(\[\[(?!Parent).*?\]\])(?=]]\s|]]$) 

組索引1包含父零件和組索引2包含的子部分。

DEMO

String input = @"[[Parent1 [[Child 1]],[[Child 2]],[[Child 3]]]] [[Parent2 [[Child 1]],[[Child 2]]]]"; 

Regex rgx = new Regex(@"(?<=^|]\s)\[\[(?<item>\S+)|(?<children>\[\[(?!Parent).*?\]\])(?=]]\s|]]$)"); 

foreach (Match m in rgx.Matches(input)) 
{ 
Console.WriteLine(m.Groups[1].Value); 
Console.WriteLine(m.Groups[2].Value); 
} 

IDEONE

0

什麼((\[\[Parent\d\]\])(\[\[Child \d\]\])+\]\])+

實際上沒有

0
(?'parent'Parent\d)|(?!^)\G(?:\[\[(?'child'.*?)]]),? 

在組 '父' 的所有父元素和組 '孩子' 所有孩子的元素

using System; 
    using System.Text.RegularExpressions; 
    public class Test 
    { 
    public static void Main() 
    { 
    String input = @"[[Parent1 [[Child 1]],[[Child 2]],[[Child 3]]]] [[Parent2 [[Child 1]],[[Child 2]]]]"; 
    Regex rgx = new Regex(@"(?<parent>Parent\d)|(?!^)\G(?:\[\[(?<child>.*?)]]),?"); 
    foreach (Match m in rgx.Matches(input)) 
    { 
    Console.WriteLine(m.Groups["parent"].Value); 
    Console.WriteLine(m.Groups["child"].Value); 
    } 
    } 
    } 

Demo

0

如何將其轉化爲更多的東西很好理解 - JSON:

string ConvertToJson(string input) 
{ 
    var elements = input 
     // replace all square brackets with quotes 
     .Replace("[[", "\"").Replace("]]", "\"") 
     // fix double quotes 
     .Replace("\"\"", "\"") 
     // split on all space-quote combos 
     .Split(new[] { " \"" }, StringSplitOptions.RemoveEmptyEntries) 
     // make sure all elements start and end with a quote 
     .Select(x => "\"" + x.Trim('"') + "\"") 
     // make all odd elements the parent item and all even the children collection 
     .Select((x, i) => (i % 2 == 0) 
      ? ("{\"item\":" + x) 
      : ",\"children\":[" + x + "]},"); 

    // turn back into string, remove unneeded comma at end and wrap in an array 
    return "[" + String.Concat(elements).Trim(',') + "]"; 
} 

輸入:

[[Parent1 [[Child 1]],[[Child 2]],[[Child 3]]]] [[Parent2 [[Child 1]],[[Child 2]]]] 

輸出:

[{"item":"Parent1","children":["Child 1","Child 2","Child 3"]},{"item":"Parent2","children":["Child 1","Child 2"]}] 

然後可以使用JSON.NET或任何玩與你一樣。

您還會注意到,此解決方案對父母被稱爲Parent沒有要求,因爲此處提供了其他解決方案。作爲獎勵,在看不到正則表達式...


爲了完整這裏使用JSON.NET到反序列化的例子:

var list = JsonConvert.DeserializeObject<dynamic>(jsonString); 

foreach (var item in list) 
{ 
    Console.WriteLine("item: {0}", item.item); 
    Console.WriteLine("Children: [{0}]", String.Join(", ", item.children)); 
} 

其輸出

項目:父母1
孩子:[孩子1,孩子2,孩子3]
項目:父母2
兒童:[兒童1,兒童2]

相關問題