krn
krn

Reputation: 6815

Ruby regex: replace double slashes in URL

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

Answers (3)

ocodo
ocodo

Reputation: 30248

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

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

Upvotes: 9

Andrew Grimm
Andrew Grimm

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

the Tin Man
the Tin Man

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

Related Questions