当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET自动为URL加上超链接的代码

ASP.NET自动为URL加上超链接的代码

2017年12月12日  | 移动技术网IT编程  | 我要评论

周晓妮sherry,郑宜兰,顺德交友网

作为一个程序员,在完成设计后还要根据程序的情况以及用户的反映不断对程序进行改进,这样才能不断地完善自己的作品。笔者在制作完软件商务网的论坛后,发现人们总喜欢在帖子中加上各种有用的url链接或email地址。而笔者当初设计时没有考虑到这一点,使得这些url链接或email地址只能以文字的形式而并不是以超链接的形式显示,其它浏览帖子的人还必须把这些url链接拷贝到浏览器中或把email地址拷贝到outlook中才能转到相应的链接地址或发送电子邮件到相应的email地址。

发现这个问题后,笔者即着手进行解决。首先是从网上查找有关这方面的现在代码,可惜的是,在搜索引擎上反复查找也没有发现这方面的文章。后来一想,干脆自己用asp.net编写一个。

要想自动显示超链接的关键在于如何能正确识别超链接,毫无疑问的,最有效的方法是用正则表达式。正则表达式是由普通字符(例如字符 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=...〉超链接〈/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=\"\" 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, "〈a href=mailto:〉〈/a〉"); 
lbcontent.text += "〈br〉"+strcontent; 
}

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

其它网友的补充:

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="" target=" rel="external nofollow" _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, "<a href=mailto:></a>");
lbcontent.text += "<br>"+strcontent;}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网