转自http://www.cnblogs.com/dudu/archive/2007/12/19/1006119.html,收藏一下.
public static string ShowUrls(string text)
{
//代码来自博客园 http://www.cnblogs.com
Regex linkRegex = new Regex(" href\\s*=\\s*(?:(?:\\\"(?<url>[^\\\"]*)\\\")|(?<url>[^\\s]* ))",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
MatchCollection linkMatchs = linkRegex.Matches(text);
string pattern = @"(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])";
MatchCollection matchs;
string clearText = Regex.Replace(text, "<[^>]*>",string.Empty, RegexOptions.Compiled);//清除html标记
matchs = Regex.Matches(clearText, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
bool flag = true;
foreach (Match m in matchs)
{
string link = "<a href=\"" + m.ToString() + "\" target=\"_new\">" + m.ToString() + "</a>";
if (linkMatchs.Count > 0)
{
foreach (Match linkMatch in linkMatchs)
{
if (linkMatch.Value.IndexOf(m.Value) > -1)
{
flag = false;
break;
}
}
}
if(flag)
{
text = text.Replace(m.ToString(), link);
}
}
return text;
}
{
//代码来自博客园 http://www.cnblogs.com
Regex linkRegex = new Regex(" href\\s*=\\s*(?:(?:\\\"(?<url>[^\\\"]*)\\\")|(?<url>[^\\s]* ))",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
MatchCollection linkMatchs = linkRegex.Matches(text);
string pattern = @"(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])";
MatchCollection matchs;
string clearText = Regex.Replace(text, "<[^>]*>",string.Empty, RegexOptions.Compiled);//清除html标记
matchs = Regex.Matches(clearText, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
bool flag = true;
foreach (Match m in matchs)
{
string link = "<a href=\"" + m.ToString() + "\" target=\"_new\">" + m.ToString() + "</a>";
if (linkMatchs.Count > 0)
{
foreach (Match linkMatch in linkMatchs)
{
if (linkMatch.Value.IndexOf(m.Value) > -1)
{
flag = false;
break;
}
}
}
if(flag)
{
text = text.Replace(m.ToString(), link);
}
}
return text;
}