c# - 如何使用维基百科中的超链接以编程方式制作 html 文本?

标签 c# regex string

我有一个字符串数组,我必须将超链接添加到数组中的项目和给定字符串的每个匹配项。 主要类似于维基百科。

类似于:

private static string AddHyperlinkToEveryMatchOfEveryItemInArrayAndString(string p, string[] arrayofstrings)

{            }

string p = "The Domesday Book records the manor of Greenwich as held by Bishop Odo of Bayeux; his lands were seized by the crown in 1082. A royal palace, or hunting lodge, has existed here since before 1300, when Edward I is known to have made offerings at the chapel of the Virgin Mary.";

arrayofstrings = {"Domesday book" , "Odo of Bayeux" , "Edward"};

returned string = @"The <a href = "#domesday book">Domesday Book</a> records the manor of Greenwich as held by Bishop <a href = "#odo of bayeux">Odo of Bayeux</a>; his lands were seized by the crown in 1082. A royal palace, or hunting lodge, has existed here since before 1300, when <a href = "#edward">Edward<a/> I is known to have made offerings at the chapel of the Virgin Mary.";

这样做的最佳方式是什么?

最佳答案

你可能很容易这样做:

foreach(string page in arrayofstrings)
{
    p = Regex.Replace(
        p, 
        page, 
        "<a href = \"#" + page.ToLower() + "\">$0</a>", 
        RegexOptions.IgnoreCase
    );
}
return p;

如果 anchor 的大小写可以和匹配的文本一样,你甚至可以去掉for循环:

return Regex.Replace(
    p,
    String.Join("|", arrayofstrings),
    "<a href = \"#$0\">$0</a>",
    RegexOptions.IgnoreCase
);

现在模式变成了 Domesday book|Odo of Bayeux|Edward,不管大小写都会找到匹配项,找到的任何内容都会放回链接文本和 href 属性。

关于c# - 如何使用维基百科中的超链接以编程方式制作 html 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13435149/

相关文章:

c# - Entity Framework - 生成类

php - 如何替换上传文件文件名中的空格

python - 使用 re.compile 根据文本文件中的未知单词的特征对其进行分类

C 中字符串中特定字母的大写

c - strncat 和 strncpy 编写安全字符串复制函数有什么区别吗?

c# - Ionic Zip 仅提取特定文件夹

c# - 添加更多参数然后在查询中使用?

c# - LINQ vs Lambda vs 匿名方法 vs 委托(delegate)

java - 如何在最新的 4.x 版本中将列表传递给 cucumber-jvm stepdef

java - ArrayList不包含字符串