如何从C#中的字符串中提取href标签?

我有一个C#函数,它返回一个字符串,格式如下:

string tableTag = "135 Boot" 

我想获得href链接并存储到另一个名为link的字符串中:

 string link = "https://stackoverflow.com/questions/22151037/how-to-extract-href-tag-from-a-string-in-c/Boot_53.html" 

我怎么能在C#中做到这一点?

如果你知道html实际上是一个xhtml(一个符合xml标准[或多或少]的html),你只需使用专用于xml的工具(通常比html更简单)解析。

 var hrefLink = XElement.Parse("135 Boot") .Descendants("a") .Select(x => x.Attribute("href").Value) .FirstOrDefault(); 

你可以使用正则表达式:

 string input= "135 Boot"; string regex= "href=\"(.*)\""; Match match = Regex.Match(input, regex); if (match.Success) { string link= match.Groups[1].Value; Console.WriteLine(link); } 

您可以使用HTML agility pack等HTML解析器来解析输入HTML并提取您要查找的信息:

 using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { var doc = new HtmlDocument(); string tableTag = "135 Boot"; doc.LoadHtml(tableTag); var anchor = doc.DocumentNode.SelectSingleNode("//a"); if (anchor != null) { string link = anchor.Attributes["href"].Value; Console.WriteLine(link); } } } 

使用HtmlAgilityPack解析HTML:

 var doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml( tableTag ); string link = doc.DocumentNode.SelectSingleNode("//a").Attributes["href"].Value;