Reputation: 6815
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(/\/\/+/, '/')
Upvotes: 5
Views: 2990
Reputation: 30248
You just need to exclude any match which is preceeded by :
url.gsub(/([^:])\/\//, '\1/')
Upvotes: 9
Reputation: 81480
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.
Upvotes: 2
Reputation: 160551
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
Upvotes: 0