Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to find URLs within a string [duplicate]

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!

like image 702
Chev Avatar asked Jan 20 '11 16:01

Chev


People also ask

How do I find the URL of a string?

To find the URLs in a given string we have used the findall() function from the regular expression module of Python.

Can we use RegEx in URL?

URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string.

What does \\ mean in RegEx?

The backslash character (\) in a regular expression indicates that the character that follows it either is a special character (as shown in the following table), or should be interpreted literally. For more information, see Character Escapes. Escaped character. Description. Pattern.


2 Answers

I am using this right now:

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

Chev


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;
}
like image 24
Sunil Agarwal Avatar answered Oct 12 '22 23:10

Sunil Agarwal