码迷,mamicode.com
首页 > 其他好文 > 详细

正则递归匹配

时间:2015-04-29 19:35:11      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

        /// <summary>
        /// 正则递归匹配
        /// </summary>
        /// <param name="dicVal">返回一个字典</param>
        /// <param name="context">要匹配的字符串</param>
        /// <param name="i">从第几个正则表达式开始匹配</param>
        /// <param name="regexes">正则表达式</param>
        private static void RegexStr(ref Dictionary<string, string> dicVal, string context, int i, string[] regexes)
        {
            if (i <= (regexes.Length - 1))
            {
                Regex regex = new Regex(ReplaceStr(regexes[i]));
                MatchCollection mc = regex.Matches(context);
                foreach (Match m in mc)
                {
                    foreach (string name in regex.GetGroupNames())//寻找被标记的组
                        if (name.StartsWith("val"))
                            dicVal.Add(name, m.Groups[name].Value);
                    RegexStr(ref dicVal, m.Value, i + 1, regexes);
                }
            }
        }

调用示例

string htmlData = "html";
string[] regexes = { 
                               @".+?",
                               @".+?",
                               @".+?"
                               };
Dictionary<string, string> dicValOut = new Dictionary<string, string>();
            RegexStr(ref dicValOut, htmlData, 0, regexes);

 

正则递归匹配

标签:

原文地址:http://www.cnblogs.com/zxxblog/p/4466636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!