gpt4 book ai didi

c# - 需要替换字符串中 anchor 标签的href

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:05 24 4
gpt4 key购买 nike

string content=" 
<br /><br /><a href="need to replace this url">Cooking School</a><br /><br /><a href="http://www.sdlm.com">Feed your senses</a><br /><br /><a href="http://www.sdl.com">Take your cooking skills to the next level. Find a cooking school near you!</a><br /><br /><a href="http:google.com"><img src="http://www.sdlm1.com/autd3umrl_u_t.jpg" /></a>
"

我需要用不同的网址替换所有 anchor 标签href值
我使用了以下功能,但出现错误
 public List<string> GetLinksFromHtml(string content)
{
string regex = @"<(?<Tag_Name>(a)|img)\b[^>]*?\b(?<URL_Type>(?(1)href|src))\s*=\s*(?:""(?<URL>(?:\\""|[^""])*)""|'(?<URL>(?:\\'|[^'])*)'))";
var matches = Regex.Matches(content, regex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
var links = new List<string>();

foreach (Match item in matches)
{
string link = item.Groups[1].Value;
links.Add(link);
}

return links;
}

谢谢你的帮助

最佳答案

尝试使用正则表达式解析 html 不是一个好主意。见 this post .使用真正的 html 解析器,如 HtmlAgilityPack .

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(content);
foreach (var a in doc.DocumentNode.Descendants("a"))
{
a.Attributes["href"].Value = "http://a.com?url=" + HttpUtility.UrlEncode(a.Attributes["href"].Value);
}

var newContent = doc.DocumentNode.OuterHtml;

关于c# - 需要替换字符串中 anchor 标签的href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12912632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com