5

I want to replace all multiple slashes in URL, apart from those in protocol definition ('http[s]://', 'ftp://' and etc). How do I do this?

This code replaces without any exceptions:

url.gsub(/\/\/+/, '/')
0

3 Answers 3

9

You just need to exclude any match which is preceeded by :

url.gsub(/([^:])\/\//, '\1/')
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, but how could I now prevent it from selecting the closest character from the left? rubular.com/r/PhVk4JSxcx
Use a negative lookbehind: %r{(?<!:)//} (not available in Ruby 1.8)
If you don't have negative lookbehind you can use a capture url.gsub(/([^:])\/\//, '\1/')
@Stuart, thanks I've updated my answer to use the back reference, since it's more widely compatible.
how about protocol-less urls like //www.domain.com/ used for http/https swaping?
2

I tried using URI:

require "uri"
url = "http://host.com//foo//bar"
components = URI.split(url)
components[-4].gsub!(/\/+/, "/")
fixed_url = [components[0], "://", components[2], components[-4]].join

But that seemed hardly better than using a regex.

Comments

0

gsub can take a block:

url = 'http://host.com//foo/bar'
puts url.gsub(%r{.//}) { |s| (s == '://') ? s : s[0] + '/' }
>> http://host.com/foo/bar

Or, as @Phrogz so kindly reminded us:

puts url.gsub(%r{(?<!:)//}, '/')
>> http://host.com/foo/bar

Comments

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.