5

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

就像是:

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.";

最好的方法是什么?

4

1 回答 1

5

你可能很容易这样做:

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

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

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

现在模式变为Domesday book|Odo of Bayeux|Edward,无论大小写如何都可以找到匹配项,找到的任何内容都会放回链接文本和href属性中。

于 2012-11-17T22:00:11.947 回答