Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regex: replace double slashes in URL

Tags:

regex

ruby

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(/\/\/+/, '/')
like image 764
krn Avatar asked Feb 11 '11 00:02

krn


2 Answers

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

url.gsub(/([^:])\/\//, '\1/')
like image 102
ocodo Avatar answered Nov 05 '22 13:11

ocodo


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.

like image 27
Andrew Grimm Avatar answered Nov 05 '22 15:11

Andrew Grimm