How to check if a URL is valid

后端 未结 9 1154
自闭症患者
自闭症患者 2020-11-28 04:23

How can I check if a string is a valid URL?

For example:

http://hello.it => yes
http:||bra.ziz, => no

If this is a valid URL

9条回答
  •  再見小時候
    2020-11-28 04:34

    This is a little bit old but here is how I do it. Use Ruby's URI module to parse the URL. If it can be parsed then it's a valid URL. (But that doesn't mean accessible.)

    URI supports many schemes, plus you can add custom schemes yourself:

    irb> uri = URI.parse "http://hello.it" rescue nil
    => #
    
    irb> uri.instance_values
    => {"fragment"=>nil,
     "registry"=>nil,
     "scheme"=>"http",
     "query"=>nil,
     "port"=>80,
     "path"=>"",
     "host"=>"hello.it",
     "password"=>nil,
     "user"=>nil,
     "opaque"=>nil}
    
    irb> uri = URI.parse "http:||bra.ziz" rescue nil
    => nil
    
    
    irb> uri = URI.parse "ssh://hello.it:5888" rescue nil
    => #
    [26] pry(main)> uri.instance_values
    => {"fragment"=>nil,
     "registry"=>nil,
     "scheme"=>"ssh",
     "query"=>nil,
     "port"=>5888,
     "path"=>"",
     "host"=>"hello.it",
     "password"=>nil,
     "user"=>nil,
     "opaque"=>nil}
    

    See the documentation for more information about the URI module.

提交回复
热议问题