如何检查 URL 是否有效 [英] How to check if a URL is valid

查看:85
本文介绍了如何检查 URL 是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查字符串是否为有效 URL?

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

例如:

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

如果这是一个有效的 URL,我如何检查它是否与图像文件相关?

If this is a valid URL how can I check if this is relative to a image file?

推荐答案

使用 Ruby 分发的 URI 模块:

Use the URI module distributed with Ruby:

require 'uri'

if url =~ URI::regexp
    # Correct URL
end

就像 Alexander Günther 在评论中所说的那样,它会检查一个字符串是否包含一个 URL.

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

要检查字符串是否是一个 URL,请使用:

To check if the string is a URL, use:

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

如果您只想检查网址(httphttps),请使用:

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

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

这篇关于如何检查 URL 是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆