【发布时间】:2019-04-12 21:07:28
【问题描述】:
我在我的函数中执行查找/替换类型的操作时遇到问题,我正在从文章中提取 anchor 并将其替换为这种格式:[链接锚点]链接和锚点将是动态的,所以我无法对值进行硬编码,到目前为止我所拥有的是:
public static string GetAndFixAnchor(string articleBody, string articleWikiCheck) {
string theString = string.Empty;
switch (articleWikiCheck) {
case "id|wpTextbox1":
StringBuilder newHtml = new StringBuilder(articleBody);
Regex r = new Regex(@"\<a href=\""([^\""]+)\"">([^<]+)");
string final = string.Empty;
foreach (var match in r.Matches(theString).Cast<Match>().OrderByDescending(m => m.Index))
{
string text = match.Groups[2].Value;
string newHref = "[" + match.Groups[1].Index + " " + match.Groups[1].Index + "]";
newHtml.Remove(match.Groups[1].Index, match.Groups[1].Length);
newHtml.Insert(match.Groups[1].Index, newHref);
}
theString = newHtml.ToString();
break;
default:
theString = articleBody;
break;
}
Helpers.ReturnMessage(theString);
return theString;
}
目前,它只返回文章原来的样子,使用传统的锚文本格式:anchor
谁能看到我做错了什么?
问候
【问题讨论】:
-
您想替换整个标签,还是只替换“href”属性的内容?不清楚
-
理想情况下,整个标签,换掉传统的锚格式:[link anchorText] 是目标。
-
为什么是正则表达式?可以使用AngleSharp、HtmlAgilityPack等HtmlParser轻松完成。
-
@colinreedy674 我之所以问,是因为您的组似乎是针对标记的位,这就是您用来设置删除和插入索引的方法。顺便说一句,您可能想使用“替换”而不是删除后跟替换。或者如 Frustrated 所说,使用 DOM 解析库。
-
你的
case "id|wpTextbox1":会触发吗?请检查。其余的可以通过Regex.Replace轻松修复。