开发者

Regular expression to find URLs within a string [duplicate]

This question already has answers here: 开发者_如何学Go Closed 12 years ago.

Possible Duplicate:

C# code to linkify urls in a string

I'm sure this is a stupid question but I can't find a decent answer anywhere. I need a good URL regular expression for C#. It needs to find all URLs in a string so that I can wrap each one in html to make it clickable.

  1. What is the best expression to use for this?

  2. Once I have the expression, what is the best way to replace these URLs with their properly formatted counterparts?

Thanks in advance!


I am using this right now:

text = Regex.Replace(text,
                @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)",
                "<a target='_blank' href='$1'>$1</a>");


Use this code

protected string MakeLink(string txt)
{
     Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);        
     MatchCollection mactches = regx.Matches(txt);        
     foreach (Match match in mactches)
     {
         txt = txt.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
     }    
     return txt;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜