2013-08-21 184 views
-1

場景:檢查一個字符串是否是一個有效的URI

a = 'some%20string';

URI(一)#拋出

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

如何檢查字符串是否是一個有效的URI在傳遞給URI之前?

+0

'URI('some%20string')'給我'#' – Stefan

+0

也許我對這個問題的回答可以幫助你:http://stackoverflow.com/questions/16234613/validate-presence-url-in-html-text/16238176#16238176 - 它與一般的URI.extract一起使用..所以你可以從你的字符串中提取出URI並傳遞它.. – Mattherick

+0

我會去有了這個答案,因爲'Addressable :: URI'具有目前爲止我所經歷的最好的URI處理:http://stackoverflow.com/a/11958835/215168 –

回答

1

我無法找到一個方法,但看source codeURI,它執行一個簡單的檢查:

case uri 
when '' 
    # null uri 
when @regexp[:ABS_URI] 
    # ... 
when @regexp[:REL_URI] 
    # ... 
else 
    raise InvalidURIError, "bad URI(is not URI?): #{uri}" 
end 

URI()使用默認的解析器,所以這樣的事情應該工作:

if URI::DEFAULT_PARSER.regexp[:ABS_URI] =~ a || URI::DEFAULT_PARSER.regexp[:REL_URI] =~ a 
    # valid 
end 
2

你仍然可以使用原來的方法問,只是在某種錯誤處理包裝它:

require 'uri' 

u = nil 
begin 
    u = URI('hi`there') 
rescue URI::InvalidURIError => e 
    puts "error: #{e}" #handle error 
end 

p u if u #do something if successful 
相關問題