2016-07-24 83 views
0

我有这个标签结构:如何从href获得标题?

<td class="team team-a "><a href="/teams/austria/sportverein-mattersburg/163/" title="Mattersburg">Mattersburg</a></td> 

我试图让title属性与此正则表达式:

return Regex.Replace(href, "<a[^>]*?title=\"([^\"]*?\"[^>]*?>", ""); 

其中href变量是内容<td>,似乎正则表达式失败,为什么?

+0

你只是缺少一个闭括号。 – horcrux

回答

1

您有语法错误,但这不是主要问题。如果您要更换,则应删除,但标题为。所以你应该删除标题本身之前和之后的所有内容。例如,

return Regex.Replace(href, ".*title=\"|\".*", ""); 

那么具体的解决方案,万一有是与title属性的一些其它标签,你需要的<a>只有标题:

.*<a[^>]*?title=\"|\".* 
2

如果你想要一个替代方案,采取看看HtmlAgilityPack:

var html = "<td class=\"team team-a\"><a href=\"/teams/austria/sportverein-mattersburg/163/\" title=\"Mattersburg\">Mattersburg</a></td>"; 

var doc = new HtmlAgilityPack.HtmlDocument(); 
doc.LoadHtml(html); 
var node = doc.DocumentNode.SelectNodes("//a") [0]; 
Console.WriteLine(node.Attributes["Title"].Value); 

当然RegEx应该更快。但根据我的经验,HtmlAgilityPack使用起来更容易,而且对于违规和无效的html,它更加宽容。