Reputation: 139
I have one problem with the expression below. I am trying to do URL validation using regular expression below:
^http(s?):\/\/(\w+\.)?[\w%\-\.$,@?^=%&:\/~\+#]+\.[\w\.$,@?^=%&:\/~\+#]+|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}+\/$
The expression above allows IP address as well as http/https:
. It accepts spaces in between url. (http://example.com). How do I restrict spaces in the expression above?
Upvotes: 0
Views: 195
Reputation: 91618
Just add in a $
(to require a line end) into your first condition:
^http(s?):\/\/(\w+\.)?[\w%\-\.$,@?^=%&:\/~\+#]+\.[\w\.$,@?^=%&:\/~\+#]+$|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}+\/$
------Add in $ here---------------------------------------------------------^
With that said, there's already built-in modules that are very good at parsing and validating URIs. I suggest using one of those.
Upvotes: 0
Reputation: 239311
Don't. This isn't a suitable use of Regular Expressions, and you will never get it right for all possible URLs. Use the URI module to actually parse the URL, and catch the exception it will raise if you feed it an invalid URL.
require 'URI'
URI("http://google.com") # => #<URI::HTTP:0x007fb08500d3a8 URL:http://google.com>
URI("http://a b") # URI::InvalidURIError: bad URI(is not URI?): http://a b
Upvotes: 4