【问题标题】:Checking if a string is a valid URI [duplicate]检查字符串是否是有效的 URI [重复]
【发布时间】:2013-08-21 09:52:20
【问题描述】:

场景:

a = 'some%20string';

URI(a) # 抛出

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

在将字符串传递给 URI 之前,如何检查字符串是否为有效 URI?

【问题讨论】:

  • URI('some%20string') 给我#<URI::Generic:0x007ffe848b8ac8 URL:some%20string>
  • 也许我对这个问题的回答可以帮助你:stackoverflow.com/questions/16234613/… - 它适用于一般的 URI.extract.. 所以你可以从你的字符串中提取 URI 并传递它..
  • 我会选择这个答案,因为Addressable::URI 拥有迄今为止我所经历过的最好的 URI 处理:stackoverflow.com/a/11958835/215168

标签: ruby-on-rails ruby


【解决方案1】:

你仍然可以使用原来的方法,只需将其包装在某种错误处理中:

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

【讨论】:

    【解决方案2】:

    我找不到方法,但是查看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
    

    【讨论】:

      猜你喜欢
      • 2011-06-17
      • 1970-01-01
      • 2016-09-16
      • 2013-02-13
      • 2023-03-31
      • 2013-08-07
      • 2016-08-20
      • 2019-05-05
      • 2019-10-04
      相关资源
      最近更新 更多