Original link:
http://www.cnblogs.com/wysky/archive/2007/12/21/1008973.html
Transfer from http://www.cnblogs.com/dudu/archive/2007/12/19/1006119.html, look at the collection.
public
static String ShowUrls ( String text) { // code from a blog Park http://www.cnblogs.com the Regex linkRegex = new new the 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;
}
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;
}
Reproduced in: https: //www.cnblogs.com/wysky/archive/2007/12/21/1008973.html