2

I have this regular expression:

^((([hH][tT][tT][pP][sS]?|[fF][tT][pP])\:\/\/)?([\w\.\-]+(\:[\w\.\&%\$\-]+)*@)?((([^\s\(\)\<\>\\\""\.\[\]\,@;:]+)(\.[^\s\(\)\<\>\\\""\.\[\]\,@;:]+)*(\.[a-zA-Z]{2,4}))|((([01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}([01]?\d{1,2}|2[0-4]\d|25[0-5])))(\b\:(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)\b)?((\/[^\/][\w\.\,\?\'\\\/\+&%\$#\=~_\-@]*)*[^\.\,\?\""\'\(\)\[\]!;<>{}\s\x7F-\xFF])?)$

It works for the most part, but it doesn't match localhost:8888.

How can I modify this expression to match localhost:8888?

7
  • That's huge! What pattern are you trying to match? Commented Oct 23, 2013 at 20:55
  • A collection of different URLs. It works, minus the string I mentioned in the OP. Commented Oct 23, 2013 at 20:56
  • 1
    Why not go with try {Uri myUri = new Uri(myString);}? Commented Oct 23, 2013 at 20:57
  • Because that won't meet my requirements, nor did I ask about matching URIs. To be fair, my question was specific. Commented Oct 23, 2013 at 20:57
  • 1
    Two problems... Commented Oct 23, 2013 at 21:02

1 Answer 1

2

All you were missing was an optional (?) on the top-level domain.

^((([hH][tT][tT][pP][sS]?|[fF][tT][pP])\:\/\/)?([\w\.\-]+(\:[\w\.\&%\$\-]+)*@)?((([^\s\(\)\<\>\\\""\.\[\]\,@;:]+)(\.[^\s\(\)\<\>\\\""\.\[\]\,@;:]+)*(\.[a-zA-Z]{2,4})?)|((([01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}([01]?\d{1,2}|2[0-4]\d|25[0-5])))(\b\:(6553[0-5]|655[0-2]\d|65[0-4]\d{2}|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)\b)?((\/[^\/][\w\.\,\?\'\\\/\+&%\$#\=~_\-@]*)*[^\.\,\?\""\'\(\)\[\]!;<>{}\s\x7F-\xFF])?)$

Matches a few examples, including the one you want:

http://www.rexfiddle.net/6tWa1Wl

I would very strongly suggest that you use the built-in Uri class in .NET though, as it handles all of this parsing and validation for you (better than any regex ever could). It was designed to be versatile, there is very little you can't do with it if you're dealing with any sort of URI (as it appears you are), and I'm pretty sure it's going to be faster than Regex, too.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for using URI class. This is an elaborate and ugly Regex that I would hate to see in code if I had to debug it.
How would you recommend that I use the Uri class when validating an ASP.Net MVC 4 ViewModel property? My current solution uses [RegularExpression("...")] as a property attribute.
Assuming you are using Data Annotations, there is a Url attribute you can use to validate URLs. If that doesn't suit your needs, write your own data validator (There are lots of tutorials on Google about how to do this).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.