1

I need a Regex validating Url:

This should be valid

http://www.google.com

https://www.google.com

but not this:

google.com

www.google.com

I know this can be done with Uri.IsWellFormedUriString for example but I need a regex. Found a couple of similar topics but does not fit my case.Thanks!

Mdb
  • 8,338
  • 22
  • 63
  • 98
  • 12
    `I know this can be done with Uri.IsWellFormedUriString for example but I need a regex`. May I ask why you need a regex? Because everytime I hear someone needing a regex the words of a wise man are echoing in my ears: `Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems`. – Darin Dimitrov Mar 22 '13 at 09:35
  • 2
    see [this](https://www.google.com.tr/search?q=url+regex+site%3Astackoverflow.com&aq=f&oq=url+regex+site%3Astackoverflow.com&aqs=chrome.0.57.6199&sourceid=chrome&ie=UTF-8&safe=active) please... – Alpay Mar 22 '13 at 09:38
  • Because the logic is already implemented using regexes for validating different types of input data but it does not handles www.google.com and goodgle.com as invalid urls. Changing it to work with Uri.IsWellFormedUriString will require some refactoring and I will just fix the reg ex for now. – Mdb Mar 22 '13 at 09:48

3 Answers3

2
(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
Gino4nx
  • 64
  • 1
  • 3
2

try this

 Regex urlchk = new Regex(@"((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,15})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&%_\./-~-]*)?", RegexOptions.Singleline | RegexOptions.IgnoreCase);
Civa
  • 2,058
  • 2
  • 18
  • 30
2

Are you sure you want regex and not this - Uri.TryCreate?

Also have you gone through this post - What is the best regular expression to check if a string is a valid URL?

Community
  • 1
  • 1