如何在C#中将文本转换为超链接?

时间:2011-02-28 14:13:41

标签: c# asp.net regex replace

我对C#和ASP.NET开发非常非常新。

我想要做的是对网页正文中出现的某些单词进行查找和替换。每当正文中出现某个单词时,我想将该单词转换为链接到我们网站上其他页面的超链接。

我不知道从哪里开始。我找到了在C#中进行查找和替换的代码,但是我没有找到任何帮助,只需阅读文档,查找某些字符串,并将它们更改为不同的字符串。

5 个答案:

答案 0 :(得分:3)

实现这一目标的几种方法。

string text = "We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defence, promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America.";

string augmentedText = text.Replace("provide", "<a href='#provide'>provide</a>");

您也可以使用正则表达式来完成此任务。

以下是将每个单词转换为大写的示例:

public static string MatchEval(Match m)
{
    return m.ToString().ToUpper();
}

static void Main(string[] args)
{
    string text = "This is some sample text.";

    Console.WriteLine(text);

    string result = Regex.Replace(text, @"\w+", new MatchEvaluator(MatchEval));

    Console.WriteLine(result);
}

希望这有帮助......祝你好运!

答案 1 :(得分:1)

在文档中查找单词或文本的最佳效果是使用正则表达式。如果您是这些人的新手,如果您打算让您的项目表现出色,我肯定会建议您仔细阅读。

您可能还想在互联网上搜索Wiki API,这将帮助您构建解决方案,而不必重新发明温水。

我非常确定以下链接将为您提供学习正则表达式的先机。下载表达式测试器并稍微玩一下。

http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx

答案 2 :(得分:0)

看起来你想要做的是创建一个打开文件并查看源代码的c#应用程序。

您可能需要使用正则表达式来获取要替换的文本的最佳匹配,在编写此文本时还需要小心,以确保它只替换整个单词,例如,如果您想要创建链接对于将你带到toms页面的单词tom,你不希望这个在明天的单词中创建链接等。

基本上我认为逻辑是在前后找到带有空格的单词,并用超链接的代码替换它。

当你第一次看到它时,正则表达式可能有点令人生畏,但是一旦你有了表达式,它就是一种非常强大的方式来执行这种事情。

答案 3 :(得分:0)

如果您有一些特定的单词,我们通常使用一些特殊的文字,如[NAME],[CLASS]来识别文字,然后执行以下操作,

  1. 使用textreader类读取html,aspx文件。
  2. 将整个文本保存在字符串中并启动字符串.replace(“[Name]”,@“...”)...将是必需的属性,
  3. 将文本重新写入具有相同扩展名的新页面。

答案 4 :(得分:0)

好的,艾米丽,请稍等一下,帮助你解决问题:

阅读以下有关如何在代码隐藏中获取正文html内容的文章: http://west-wind.com/weblog/posts/481.aspx

假设您将Render()输出存储在名为_pageContent

的变量中

我现在使用任何正则表达式,因为我没有时间正确地思考一个正则表达式。你可以自己玩一下。以下链接可能会指向您:Regex to match multiple strings

public static void ChangeWordsToLinks()
{
  Dictionary<string, string> _wordLinkCollection = new Dicationary<string, string>();
  // fill the collection which will replace words by links here
  // Additionally you can fetch this from a database and loop 
  // through a DataTable to fill this collection
  _wordLinkCollection.add("foo", "http://www.foobar.com");
  _wordLinkCollection.add("bar", "http://www.barfoo.com");

  // this is lazy code and SHOULD be optimized to a single RegExp string.
  foreach(KayValuePair<string, string> pair in _wordLinkCollection)
  {
    _pageContent.Replace(String.Format(" {0} ", pair.Key), 
        String.Format("<a href='{0}'>{1}</a>", pair.Value, pair.Key));
  }
}

如果我能为你提供任何帮助,我很高兴