How to check if a URL is valid

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

    Use the URI module distributed with Ruby:

    require 'uri'
    
    if url =~ URI::regexp
        # Correct URL
    end
    

    Like Alexander Günther said in the comments, it checks if a string contains a URL.

    To check if the string is a URL, use:

    url =~ /\A#{URI::regexp}\z/
    

    If you only want to check for web URLs (http or https), use this:

    url =~ /\A#{URI::regexp(['http', 'https'])}\z/
    

提交回复
热议问题