现在的位置: 首页 > 综合 > 正文

url自动转成链接

2012年05月24日 ⁄ 综合 ⁄ 共 1095字 ⁄ 字号 评论关闭

//url转链接 

//2008-7-7

Regex UrlRegex = new Regex(@"((http|ftp|https):\/\/(([\w.]+\/?)[\S]*))|((www.)([\w.]+\/?)\S*)");
Text =
UrlRegex.Replace(Text, "<a href=\"http://$3$5\"
target=\"_blank\" style=\"color: #004299\">$1$5</a>");

//Email转链接
 Regex EmailRegex = new
Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)", RegexOptions.IgnoreCase |
RegexOptions.Compiled);
Text = EmailRegex.Replace(Text, "<a href=\"mailto:$1\" target=\"_blank\"
style=\"color:#004299\">$1</a>");

//2008-7-8

上面有BUG,把https和ftp都变成了http,下面做了修正:

Regex UrlRegex = new
Regex(@"((http|ftp|https):\/\/(([\w.]+\/?)[\S]*))");//查找带有http|ftp|https的URL
Text
= UrlRegex.Replace(Text, "<a href=\"$1\" target=\"_blank\" style=\"color:
#004299\">$1</a>");

UrlRegex = new
Regex(@"((?<!(http|ftp|https):\/\/)((www.)([\w.]+\/?)\S*))");//查找不带有http|ftp|https,但以www.开头的URL

Text
= UrlRegex.Replace(Text, "<a href=\"http://$1\"
target=\"_blank\" style=\"color: #004299\">$1</a>");Regex
EmailRegex = new Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)",
RegexOptions.IgnoreCase | RegexOptions.Compiled);//查找EMAIL

Text =
EmailRegex.Replace(Text, "<a href=\"mailto:$1\"
target=\"_blank\" style=\"color:#004299\">$1</a>");

抱歉!评论已关闭.