How to check if a URL is valid

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

    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
    

提交回复
热议问题