[英]Get anchor tag HREF and VALUE
我有一個看起來像這樣的字符串:
<a href="http://forum.tibia.com/forum/?action=board&boardid=476">Amera</a><br><font class="ff_info">This board is for general discussions related to the game world Amera.</font>
我如何才能忽略/刪除</a>
之后的所有內容,然后僅獲得以下網址: http://forum.tibia.com/forum/?action=board&boardid=476
: http://forum.tibia.com/forum/?action=board&boardid=476
Amera
和值Amera
所以之后,我想要2個變量及其值,例如:
string url = "http://forum.tibia.com/forum/?action=board&boardid=476";
和
string value = "Amera";
我試圖這樣做來獲得價值:
string value = System.Text.RegularExpressions.Regex.Replace(MYSTRING, "(<[a|A][^>]*>|)", "");
但它返回:
Amera</a><br><font class="ff_info">This board is for general discussions related to the game world Amera.</font>
要獲取URL,請嘗試以下正則表達式模式:/ /href=\\"(.*)\\"/
...並獲取> Amera </a>
之間的值,請使用類似如下的模式: >(.+?)</a>
盡管這似乎還不完美
如果a
標簽將不包含多種屬性,你可以用這個唯一的網址:
\bhref="(.*?)"
URL和文本的復雜程度略高一些:
<a\b[^>]*?\bhref="([^"]*?)"[^>]*?>(.*?)<\/a>
因此,在C#代碼中(引號需要轉義!):
var html = "<a href=\"http://forum.tibia.com/forum/?action=board&boardid=476\">Amera</a><br><font class=\"ff_info\">This board is for general discussions related to the game world Amera.</font>";
var match = Regex.Match(html, "<a\\b[^>]*?\\bhref=\"([^\"]*?)\"[^>]*?>(.*?)<\\/a>", RegexOptions.IgnoreCase);
if (match.Success) {
var url = match.Groups[1];
var text = match.Groups[2]
}
嘗試這個:
HtmlDocument dc = new HtmlAgilityPack.HtmlDocument();
dc.LoadHtml("<a href='http://forum.tibia.com/forum/?action=board&boardid=476'>Amera</a><br><font class='ff_info'>This board is for general discussions related to the game world Amera.</font>");
foreach (HtmlNode link in dc.DocumentNode.SelectNodes("a"))
{
string url = link.Attributes["href"].Value; // http://forum.tibia.com/forum/?action=board&boardid=476
string value = link.InnerText; // Amera
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.