在asp.net中自动给url地址加上超链接

    要想自动显示超链接的关键在于如何能正确识别超链接,毫无疑问的,最有效的方法是用正则表达式。正则表达式是由普通字符(例如字符 a 到 z)以及特殊字符(称为元字符)组成的文字模式,描述了一种字符串匹配的模式,可以用来检查一个串是否含有某种子串、将匹配的子串做替换或者从某个串中取出符合某个条件的子串等。.net基础类库中包含有一个名字空间和一系列可以充分发挥规则表达式威力的类,用它就可以自动探测出文字中的url链接或email地址。下面我具体讲讲如何用asp.net(c#)一步步实现我们的目的:

首先,要想在asp.net(c#)中使用正则表达式就必须把 system.text.regularexpressions 这个命名空间包含进来:

using system.text.regularexpressions;

第二步是用正则表达式识别url超链接:

regex urlregex = new regex(@"(http:\/\/([\w.]+\/@)\s*)",
   regexoptions.ignorecase|regexoptions.compiled);

这里的代码是用正则表达式识别email地址:

regex emailregex = new regex(@"([a-za-z_0-9.-]+\@[a-za-z_0-9.-]+\.\w+)",
   regexoptions.ignorecase|regexoptions.compiled);

第三步,当程序已经识别出url超链接或email地址后,必须用<a href=/knowskycom/...>超链接</a>对这些超链接进行替换,这样才能把这些文字显示为链接的形式。我这里把它们全部包含在函数中:

private void button1_click(object sender, system.eventargs e)
{
   string strcontent = inputtextbox.text;
   regex urlregex = new regex(@"(http:\/\/([\w.]+\/@)\s*)",
                    regexoptions.ignorecase| regexoptions.compiled);
   strcontent = urlregex.replace(strcontent,
                "<a href=/knowskycom/\"\" target=\"_blank\"></a>");
   regex emailregex = new regex(@"([a-za-z_0-9.-]+\@[a-za-z_0-9.-]+\.\w+)",
      regexoptions.ignorecase| regexoptions.compiled);
   strcontent = emailregex.replace(strcontent, "mailto:></a>");
   lbcontent.text += "<br>"+strcontent;
}

通过以上几步,你就可以在网页上自动显示超链接以及email地址了。

原文地址:https://www.cnblogs.com/tuyile006/p/395570.html