How to check if a URL is valid

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

    This is a fairly old entry, but I thought I'd go ahead and contribute:

    String.class_eval do
        def is_valid_url?
            uri = URI.parse self
            uri.kind_of? URI::HTTP
        rescue URI::InvalidURIError
            false
        end
    end
    

    Now you can do something like:

    if "http://www.omg.wtf".is_valid_url?
        p "huzzah!"
    end
    
    0 讨论(0)
  • 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/
    
    0 讨论(0)
  • 2020-11-28 04:50

    You could also use a regex, maybe something like http://www.geekzilla.co.uk/View2D3B0109-C1B2-4B4E-BFFD-E8088CBC85FD.htm assuming this regex is correct (I haven't fully checked it) the following will show the validity of the url.

    url_regex = Regexp.new("((https?|ftp|file):((//)|(\\\\))+[\w\d:\#@%/;$()~_?\+-=\\\\.&]*)")
    
    urls = [
        "http://hello.it",
        "http:||bra.ziz"
    ]
    
    urls.each { |url|
        if url =~ url_regex then
            puts "%s is valid" % url
        else
            puts "%s not valid" % url
        end
    }
    

    The above example outputs:

    http://hello.it is valid
    http:||bra.ziz not valid
    
    0 讨论(0)
提交回复
热议问题