[英]Match nested HTML tags
在C#应用程序中,我想将每个HTML“字体”标记与“颜色”属性进行匹配。
我有以下文字:
1<font color="red">2<font color="blue">3</font>4</font>56
我想要一个包含以下项目的MatchCollection:
[0] <font color="red">234</font>
[1] <font color="blue">3</font>
但是当我使用此代码时:
Regex.Matches(result, "<font color=\"(.*)\">(.*)</font>");
我得到的MatchCollection是以下内容:
[0] <font color="red">2<font color="blue">3</font>4</font>
如何使用C#获得我想要的MatchCollection?
谢谢。
“ HTML”上的正则表达式是反模式。 只是不要这样做。
为了引导您走上正确的道路,请查看HTML Agility Pack可以做什么:
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"1<font color=""red"">2<font color=""blue"">3</font>4</font>56");
var fontElements = doc.DocumentNode.Descendants("font");
var newNodes = fontElements.Select(fe => {
var newNode = fe.Clone();
newNode.InnerHtml = fe.InnerText;
return newNode;
});
var collection = newNodes.Select(n => n.OuterHtml);
现在,在collection
我们有以下字符串:
<font color="red">234</font>
<font color="blue">3</font>
嗯...好可爱
Matches m = Regex.Matches(result, "<font color=\"(.*?)\">(.*?)</font>");
//add a ? after the * and print the result .you will know how to get it.
使用HTML Agility Pack和XPath查询来确保出现color属性的一种方式:
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.OptionFixNestedTags = true;
String html = "1<font color=\"red\">2<font color=\"blue\">3</font>4</font>56";
htmlDoc.LoadHtml(html);
HtmlNodeCollection fontTags = htmlDoc.DocumentNode.SelectNodes(".//font[@color]");
foreach (HtmlNode fontTag in fontTags)
{
Console.WriteLine(fontTag.InnerText);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.