有个字符串以"["和"]"做分割符,左右括号必然是匹配的,每对括号里包含一个关键字和它的属性,我想要的结果是取出每个关键字所对应的属性
举个例子
1. 最简单的: A[B, Attr2],Attr1   那么这个字符串有两个关键字 "A"和"B", Attr1是A的属性,Attr2是B的属性。
2. 嵌套的: A[B[[C, Attr3], [D, Attr4]], Attr2], Attr1  那么这个字符串有4个关键字 "A" "B" "C"和"D", Attr1是A的属性,Attr2是B的属性, Attr3是C的属性,Attr4是D的属性。这种分析程序应该从什么方面下手,大家提供点思路吧,谢啦

解决方案 »

  1.   

    先将最里面的一层脱壳,处理后删除.
    A[B, Attr2],Attr1 
    脱壳后变成
    A,Attr1 
    下一层处理...
      

  2.   


    static void Main()
    {
     List<string>list=new List<string>();
    string str="A[B[[C, Attr3], [D, Attr4]], Attr2], Attr1 ";
      
      GetStr(ref str,ref list);
      while (Regex.IsMatch(str,@"\[,\s*\]"))
      {
        str=Regex.Replace(str,@"\[,\s*\]","");
    GetStr(ref str,ref list);
      }
      list.Add(str); 
      list.OrderBy(l=>l).ToList().ForEach(l=>Console.WriteLine(l));
      /*
    A, Attr1 
    B, Attr2
    C, Attr3
    D, Attr4  */
    }static void  GetStr(ref string str,ref List<string>list)

     foreach(Match m in Regex.Matches(str,@"\[(\w+,[^\]]+)]"))
     {
       list.Add(m.Groups[1].Value);
       str=str.Replace(m.Value,""); 
     }
    }
      

  3.   

    public static void Test()
    {
        string str = "A[B[[C, Attr3], [D, Attr4]], Attr2], Attr1";
        Dictionary<string, string> result = new Dictionary<string, string>();
        Regex reg = new Regex(@"(?n)(?<key>[^\[\]]+)(?<sub>((?<o>\[)|(?<-o>\])|[^\[\]])*(?(o)(?!)))\s*,\s*(?<value>\w+)");
        Action<string> GetValues = null;
        GetValues = s =>
            {
                MatchCollection mc = reg.Matches(s);
                foreach (Match m in mc)
                {
                    result.Add(m.Groups["key"].Value, m.Groups["value"].Value);
                    if (m.Groups["sub"].Success)
                    {
                        GetValues(m.Groups["sub"].Value);
                    }
                }                
            };
        GetValues(str);
        foreach (var item in result)
        {
            Console.WriteLine(item.Key + "," + item.Value);
        }
    }输出
    A,Attr1
    B,Attr2
    C,Attr3
    D,Attr4