How to check if a URL is valid

后端 未结 9 1145
自闭症患者
自闭症患者 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:36

    Similar to the answers above, I find using this regex to be slightly more accurate:

    URI::DEFAULT_PARSER.regexp[:ABS_URI]
    

    That will invalidate URLs with spaces, as opposed to URI.regexp which allows spaces for some reason.

    I have recently found a shortcut that is provided for the different URI rgexps. You can access any of URI::DEFAULT_PARSER.regexp.keys directly from URI::#{key}.

    For example, the :ABS_URI regexp can be accessed from URI::ABS_URI.

提交回复
热议问题