tags:

views:

175

answers:

5

I have found many examples of how to match particular types of URL-s in PHP and other languages. I need to match any URL from my C# application. How to do this? When I talk about URL I talk about links to any sites or to files on sites and subdirectiories and so on.

I have a text like this: "Go to my awsome website http:\www.google.pl\something\blah\?lang=5" or else and I need to get this link from this message. Links can start only with www. too.

+3  A: 

I am not sure exactly what you are asking, but a good start would be the Uri class, which will parse the url for you.

DanDan
+3  A: 

If you need to test your regex to find URLs you can try this resurce

http://gskinner.com/RegExr/

it will test your regex while you're writing it.

In c# you can use regex for example as below:

Regex r = new Regex("(?<Protocol>\w+):\/\/(?<Domain>[\w@][\w.:@]+)\/?[\w\.?=%&=\-@/$,]*");
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
while (m.Success) 
{
   //do things with your matching text 
   m = m.NextMatch();
}
michele
A: 
Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
almog.ori
+2  A: 

Here's one defined for URL's.

^http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?$

http://msdn.microsoft.com/en-us/library/ms998267.aspx

David Liddle
A: 

This will return a match collection of all matches found within "yourStringThatHasUrlsInIt":

var pattern = @"((ht|f)tp(s?)\:\/\/|~/|/)?([w]{2}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?";
var regex = new Regex(pattern);
var matches = regex.Matches(yourStringThatHasUrlsInIt);

The return will be a "MatchCollection" which you can read more about here:

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchcollection.aspx

free-dom