/// <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);
时间: 2024-10-07 12:47:59