首先,要想在ASP.NET(C#)中使用正则表达式就必须把 System.Text.RegularExpressions 这个命名空间包含进来
using System.Text.RegularExpressions;
第二步是用正则表达式识别URL超链接:
代码如下:Regex urlregex = new Regex(@"(http:\/\/([\w.]+\/?)\S*)",这里的代码是用正则表达式识别Email地址:
代码如下:Regex emailregex = new Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)",第三步,当程序已经识别出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,"");
regex emailregex = new regex(@"([a-za-z_0-9.-]+@[a-za-z_0-9.-]+.w+)",regexoptions.ignorecase| regexoptions.compiled);
strcontent = emailregex.replace(strcontent, "");
lbcontent.text += "
"+strcontent;}