• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
轻装前行
博客园    首页    新随笔    联系   管理    订阅  订阅
正则表达式解析对象

代码胜过一切!

Program.cs

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ConAppRegex
{
    public static class RegexHelper
    {
        public static readonly Regex regValidateObject = new Regex(@"(?n)(?<name>[^{},]+)\{(?<data>((?<o>\{)|(?<-o>\})|[^{}]+)+(?(o)(?!)))\}", RegexOptions.Compiled);
        public static readonly Regex regReplaceComma = new Regex(@",{2,}", RegexOptions.Compiled);
    }

    public class Program
    {
        static void Main(string[] args)
        {
            string s = "AAA.{BBB},CCC.{DDD,EEE,FFF.{GGG}},HHH.{*},JJJ.{*,XXX.{YYY}},KKK.{LLL.{MMM},NNN,OOO},PPP.{QQQ,RRR.{SSS},TTT.{UUU,VVV},WWW}";
            // 展开后,得到如下效果:
            /*string s = @"
            AAA.
            {
                BBB
            },
            CCC.
            {
                DDD,
                EEE,
                FFF.{GGG}
            },
            HHH.
            {
                *
            },
            JJJ.
            {
                *,
                XXX.{YYY}
            },
            KKK.
            {
                LLL.{MMM},
                NNN,
                OOO
            },
            PPP.
            {
                QQQ,
                RRR.{SSS},
                TTT.{UUU,VVV},
                WWW
            }";
            */
            List<MyData> result = new List<MyData>();
            MatchCollection mc = RegexHelper.regValidateObject.Matches(s);
            foreach (Match m in mc)
            {
                MyData d = new MyData(m.Groups["name"].Value, m.Groups["data"].Value);
                foreach (Match m1 in RegexHelper.regValidateObject.Matches(d.Code))
                {
                    MyData d2 = new MyData(m1.Groups["name"].Value, m1.Groups["data"].Value);
                    foreach (Match m2 in RegexHelper.regValidateObject.Matches(d2.Code))
                    {
                        MyData d3 = new MyData(m2.Groups["name"].Value, m2.Groups["data"].Value);
                        d2.Inner.Add(d3);
                    }
                    d.Inner.Add(d2);
                }
                result.Add(d);
            }
            //输出
            foreach (MyData item in result)
            {
                Console.WriteLine(item.Name);
                Console.WriteLine("{");
                Console.WriteLine(item.ReplacedCode);
                foreach (MyData innerItem in item.Inner)
                {
                    Console.WriteLine(innerItem.ReplacedCode);
                }
                //Console.WriteLine(Regex.Replace(item.Code, "(?<!{[^}]+),", "\r\n"));

                //对于 KKK 对象,我想到 NNN 和 OOO 对象,并用逗号连接起来。
                //对于 PPP 对象,我想得到 QQQ 和 WWW 对象,并用逗号连接起来。正则表达式该怎么写呢?

                //foreach (MyData innerItem in item.Inner)
                //{
                //    Console.WriteLine(innerItem.Name);
                //    Console.WriteLine("{");
                //    Console.WriteLine(innerItem.Code);
                //    Console.WriteLine("}");
                //}

                Console.WriteLine("}");
            }
            Console.ReadKey();
        }
    }

    public class MyData
    {
        private string _code;

        public MyData(string name, string code)
        {
            this.Name = name;
            this.Code = code;
        }
        public string Name { get; set; }

        public string Code 
        {
            get
            {
                return _code;
            }
            set
            {
                if (value != _code)
                {
                    OnPropertyCodeChanged(value);
                }
                _code = value;
            }
        }

        private void OnPropertyCodeChanged(string newValue)
        {
            if (string.IsNullOrEmpty(newValue))
            {
                return;
            }
            //string replacedCode1 = RegexHelper.reg.Replace(newValue, string.Empty).SplitWithCommaAndJoinWithComma();   //方案1 : 主要是利用 String.Split 分割(移除了空实体)后的数组来循环 Join
            string replacedCode2 = RegexHelper.regReplaceComma.Replace(RegexHelper.regValidateObject.Replace(newValue, string.Empty), ",").Trim(',');  //方案2:主要是利用正则表达式来把2个或2个以上的逗号替换为一个逗号,效率应该比方案1高一些
            this.ReplacedCode = replacedCode2;
        }

        /// <summary>
        /// 替换后剩下的字符串
        /// </summary>
        public string ReplacedCode { get; private set; }
        
        public List<MyData> Inner = new List<MyData>();
    }
}

IEnumerableExtender.cs

using System.Collections.Generic;
using System.Text;
using System;

namespace ConAppRegex
{
    public static class IEnumerableExtender
    {

        /// <summary>
        /// 将集合中的每个元素用英文的逗号连接起来,返回一个字符串
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="source">要连接的集合</param>
        /// <returns>字符串</returns>
        public static string JoinWithComma<T>(this IEnumerable<T> source)
        {
            if (source == null)
            {
                return null;
            }
            StringBuilder sbResult = new StringBuilder();
            foreach (T item in source)
            {
                sbResult.Append(item.ToString() + ",");
            }
            return sbResult.ToString().Trim(',');
        }

        /// <summary>
        /// 取出字符串中的多个逗号成一个逗号
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string SplitWithCommaAndJoinWithComma(this string source)
        {
            if (string.IsNullOrEmpty(source))
            {
                return source;
            }
            return source.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).JoinWithComma();
        }
    }
}

谢谢浏览!

posted on 2011-02-27 00:26  轻装前行  阅读(351)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3