2016-09-28 85 views
3

我有這種格式的URL:如何分析與斜線的URL在用戶信息部分

https://clientjiberish:[email protected]/users?username=tralala 

當我這樣做:

url = 'https://clientjiberish:[email protected]/users?username=tralala' 
uri = URI(url) 

我得到我所需要的。

uri.host => "api.example.com" 
uri.userinfo => "clientjiberish:clientsecretjiberish" 
uri.path => '/users' 
uri.scheme => 'https' 

當用戶信息部件中存在正斜槓時,問題就會出現。我沒有權力改變提供API密鑰的API,所以我需要找出一種方法來提取URI中提到的部分。

這裏你可以測試一下URI的例子:

url = 'https://clientjiberish:client/[email protected]/users?username=tralala' 
uri = URI(url) 

錯誤:

URI::InvalidURIError: bad URI(is not URI?)

我發現,你可以創建自己的解析器是這樣的:

parser = URI::Parser.new(:RESERVED => ";/?:@&=+$,\\[\\]") 
uri = parser.parse(url) 

但我不知道正則表達式使其工作。

+1

你能不能用'%2F''在'client/secretjiberish'中跳過正斜槓? – Rashmirathi

+0

@Rashmirathi 我該如何訪問它?如果我這樣做: escaped_url = URI.escape(url,'/')然後是URI(url)我不能使用任何URI方法,因爲它們都返回nil。 –

+0

我的意思是隻在'clientjiberish:client/secretjiberish'部分轉義它,所以url變成'https:// clientjiberish:client%[email protected]/users?username = tralala'。 – Rashmirathi

回答

0
url = 'https://clientjiberish:client/[email protected]/users?username=tralala' 
USER_INFO_REGEX = /\Ahttp[s]+:\/\/(.*)@.*\z/i 
user_info = USER_INFO_REGEX.match(url)[1] 
parsed_user_info = user_info.gsub(/\//, '%2F') 
url = url.gsub(Regexp.new(user_info), parsed_user_info) 
uri = URI(url) 

USER_INFO_REGEXhttps://@api.example.com...之間的字符串相匹配。只需轉義用戶信息字符串並將其替換爲url即可。

相關問題