代码:{
第一层
{
第二层
}
}用正则后想取得两个数据.
1,
第一层
{
第二层
}2,
第二层如何写?

解决方案 »

  1.   


                string str = @"{
    第一层
    {
    第二层
    }
    }
    ";
                Match m = new Regex(@"(?<=\{)[^{}]+(?:(?:(?<Open>\{)([^{}]+))*(?:(?<-Open>\})[^{}]*)*)*(?=\})").Match(str);
                Console.WriteLine(m.Value);
                foreach (Capture c in m.Groups[1].Captures)
                    Console.WriteLine(c.Value);
    /*第一层
    {
    第二层
    }
    第二层
    */
      

  2.   


    string r1 = Regex.Replace(s, @"^\s*{|}\s*$", "");
    string r2 = Regex.Match(s, @"{([^{}]+)}").Groups[1].Value;
      

  3.   

            static Regex reg = new Regex(@"(?<=\{)[^{}]+((?:(?<Open>\{)(?:[^{}]+))*(?:(?<-Open>\})[^{}]*)*)*(?=\})");
            static void Main(string[] args)
            {
                string str = @"{
    第一层
    {
    第二层
    {
    第三层
    {
    第四层
    }
    }
    }
    }
    ";
                GetValue(str);
                Console.ReadKey();
            }
            public static void GetValue(string str)
            {
                Match m = reg.Match(str);
                if (m.Success)
                {
                    Console.WriteLine(m.Value);
                    GetValue(m.Value);
                }
            }
    /*第一层
    {
    第二层
    {
    第三层
    {
    第四层
    }
    }
    }
    第二层
    {
    第三层
    {
    第四层
    }
    }
    第三层
    {
    第四层
    }
    第四层
    */
      

  4.   


            static Regex reg = new Regex(@"(?<=\{)[^{}]+((?:(?<Open>\{)(?:[^{}]+))*(?:(?<-Open>\})[^{}]*)*)*(?=\})");
            static void Main(string[] args)
            {
                string str = @"{
    第一层
    {
    第二层
    {
    第三层
    {
    第四层
    {
    第五层
    {
    第六层
    }
    }
    }
    }
    }
    }
    ";
                GetValue(str);
                Console.ReadKey();
            }
            public static void GetValue(string str)
            {
                Match m = reg.Match(str);
                if (m.Success)
                {
                    Console.WriteLine(m.Value);
                    GetValue(m.Value);
                }
            }
    /*
    第一层
    {
    第二层
    {
    第三层
    {
    第四层
    {
    第五层
    {
    第六层
    }
    }
    }
    }
    }第二层
    {
    第三层
    {
    第四层
    {
    第五层
    {
    第六层
    }
    }
    }
    }第三层
    {
    第四层
    {
    第五层
    {
    第六层
    }
    }
    }第四层
    {
    第五层
    {
    第六层
    }
    }第五层
    {
    第六层
    }第六层
    */