将文章内容中没有链接的地址转换为链接。
代码如下:
publicstaticstringShowUrls(stringtext)
{
//代码来自博客园
RegexlinkRegex=newRegex("href\\s*=\\s*(?:(?:\\\"(?<url>[^\\\"]*)\\\")|(?<url>[^\\s]*))",
RegexOptions.IgnoreCase|piled);
MatchCollectionlinkMatchs=linkRegex.Matches(text);
stringpattern=@"(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])";
MatchCollectionmatchs;
stringclearText=Regex.Replace(text,"(<br>|<br/>)","",RegexOptions.IgnoreCase);
clearText=Regex.Replace(clearText,"<[^>]*>",string.Empty,piled);//清除html标记
matchs=Regex.Matches(clearText,pattern,RegexOptions.IgnoreCase|piled);
boolflag1=true;
for(inti=0;i<matchs.Count;i++)
{
Matchm=matchs[i];
stringlink="<ahref=\""+m.ToString()+"\"target=\"_blank\">"+m.ToString()+"</a>";
if(linkMatchs.Count>0)
{
foreach(MatchlinkMatchinlinkMatchs)
{
if(linkMatch.Value.IndexOf(m.Value)>-1)
{
flag1=false;
break;
}
}
}
if(flag1)
{
boolflag2=true;
for(intj=0;j<i;j++)
{
if(m.ToString()==matchs[j].ToString())
{
flag2=false;
}
}
if(flag2)
{
text=text.Replace(m.ToString(),link);
}
}
}
returntext;
}