How to match URL in c#?

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.


Here's one defined for URL's.

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

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


Microsoft has a nice page of some regular expressions...this is what they say (works pretty good too)

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

http://msdn.microsoft.com/en-us/library/ff650303.aspx#paght000001_commonregularexpressions


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

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();
}

Tags:

C#

Url

Regex