-1

I am using a regex to validate a URL in c#. Regex is:

^((((http(s)?|ftp(s)?):(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:([a-zA-Z]{1,}\.)|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$

It is working fine for the url like : http://stackoverflow.com, stackoverflow.com but I also want to validate http://localhost:1234 and localhost:1234.

Syed Uzair Uddin
  • 3,296
  • 7
  • 31
  • 47
  • 1
    See [What is the best regular expression to check if a string is a valid URL?](http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url) – Wiktor Stribiżew Dec 08 '16 at 07:39
  • 1
    It must be possible. Everything is possible with Regex. Even parsing HTML is [almost possible](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). If you want to understand your own code in February 2017, then use something else. – Thomas Weller Dec 08 '16 at 07:45

1 Answers1

2

Try out this regex instead:

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