使用正则找出XML(HTML)里不匹配的标签
找到HTML里错误的Tag,主要是为了方便在程序里将HTML以XML方式读取分析.
通过正则表达式来找到标签,然后通过堆栈方式处理,使用C#编写.
string html = @"此处省略";
Regex regExp = new Regex(@"<(/?(\w+))[^>]*>", RegexOptions.Compiled);
Match m = regExp.Match(html);
Stack<Match> tags = new Stack<Match>();
List<Match> err = new List<Match>();
while (m.Success)
{
if (!m.Value.StartsWith("</"))
{
tags.Push(m);
}
else
{
if (string.Compare(tags.Peek().Groups[2].Value, m.Groups[2].Value, true) == 0) tags.Pop();//移除
else err.Add(m);
}
m = m.NextMatch();
}
foreach (Match e in tags)//前面<...多余的
{
Console.WriteLine(e.Value + "位置:" + e.Index + "长度:" + e.Length);
}
foreach (Match e in err)//后面</...多余的
{
Console.WriteLine(e.Value + "位置:" + e.Index + "长度:" + e.Length);
}
沙发咯 这个程序写的好棒,好精悍 Regex regExp = new Regex(@"]*>", RegexOptions.Compiled); 这句用法没有见过!
谢谢分享