在ASP.NET中自动给URL地址加上超链接

下面我具体讲讲如何用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文本后,必须用超链接文本对这些超链接文本进行替换,这样才能把这些文字显示为链接的形式。我这里把它们全部包含在函数中: 
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, ""); lbContent.Text += "
"+strContent; } 

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

posted on 2008-07-28 12:18  9who  阅读(261)  评论(0编辑  收藏  举报

导航