prasad_g
prasad_g

Reputation: 139

Regular expression to avoid Spaces

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

Answers (2)

Mike Christensen
Mike Christensen

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---------------------------------------------------------^

Example

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

user229044
user229044

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

Related Questions