1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 将地址转换为链接的正则表达式(regex url href)

将地址转换为链接的正则表达式(regex url href)

时间:2020-11-19 07:12:35

相关推荐

将地址转换为链接的正则表达式(regex url href)

将文章内容中没有链接的地址转换为链接。

代码如下:

publicstaticstringShowUrls(stringtext)

{

//代码来自博客园

RegexlinkRegex=newRegex("href\\s*=\\s*(?:(?:\\\"(?<url>[^\\\"]*)\\\")|(?<url>[^\\s]*))",

RegexOptions.IgnoreCase|piled);

MatchCollectionlinkMatchs=linkRegex.Matches(text);

stringpattern=@"(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])";

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;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。