-1
a = 'some%20string';
URI(一)#抛出
URI::InvalidURIError: bad URI(is not URI?)
如何检查字符串是否是一个有效的URI在传递给URI之前?
a = 'some%20string';
URI(一)#抛出
URI::InvalidURIError: bad URI(is not URI?)
如何检查字符串是否是一个有效的URI在传递给URI之前?
我无法找到一个方法,但看source code为URI
,它执行一个简单的检查:
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
你仍然可以使用原来的方法问,只是在某种错误处理包装它:
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
'URI('some%20string')'给我'#' –
Stefan
也许我对这个问题的回答可以帮助你:http://stackoverflow.com/questions/16234613/validate-presence-url-in-html-text/16238176#16238176 - 它与一般的URI.extract一起使用..所以你可以从你的字符串中提取出URI并传递它.. – Mattherick
我会去有了这个答案,因为'Addressable :: URI'具有目前为止我所经历的最好的URI处理:http://stackoverflow.com/a/11958835/215168 –