2014-09-19 43 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]

相关问题