Ruby regex: replace double slashes in URL

I want to replace all multiple slashes in the URL except those specified in the protocol definition ('http [s]: //', 'ftp: //', etc.). How to do it?

This code replaces without exception:

url.gsub(/\/\/+/, '/')
+5
source share
3 answers

You just need to exclude any match that precedes :

url.gsub(/([^:])\/\//, '\1/')
+9
source

I tried using a 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 it looked a little better than using a regular expression.

+2
source

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
0
source

All Articles