如何使用 C# 仅从 html 锚标记获取 href 值谢谢
string ref="<a href="http://www.google.com"></a>";
//i want get result from
//string ref like
//http://www.google.com
Run Code Online (Sandbox Code Playgroud)
您可以使用 HTML 解析库,例如Html Agility Pack。例如:
using System;
using HtmlAgilityPack;
class Program
{
static void Main()
{
var doc = new HtmlDocument();
doc.LoadHtml("<a href=\"http://www.google.com\"></a>");
var nodes = doc.DocumentNode.SelectNodes("a[@href]");
foreach (var node in nodes)
{
Console.WriteLine(node.Attributes["href"].Value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想在没有HtmlAgilityPack 的情况下执行此操作,则可以使用正则表达式执行此操作:
string ref= @"<a href=""http://www.google.com"">test</a>";
var regex = new Regex("<a [^>]*href=(?:'(?<href>.*?)')|(?:\"(?<href>.*?)\")", RegexOptions.IgnoreCase);
var urls = regex.Matches(ref).OfType<Match>().Select(m => m.Groups["href"].Value).SingleOrDefault();
Run Code Online (Sandbox Code Playgroud)
希望对您有帮助。