如何检查给定的字符串是否是有效的URL地址?

我对正则表达式的知识是基本的,不允许我从我已经在网上看到的数百个正则表达式中进行选择。


当前回答

要将URL匹配到域:

(^(\bhttp)(|s):\/{2})(?=[a-z0-9-_]{1,255})\.\1\.([a-z]{3,7}$)

可以简化为:

(^(\bhttp)(|s):\/{2})(?=[a-z0-9-_.]{1,255})\.([a-z]{3,7})

后者不检查结束行的结束,以便稍后使用它创建具有完整路径和查询字符串的完整URL。

其他回答

function validateURL(textval) {
            var urlregex = new RegExp(
            "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$");
            return urlregex.test(textval);
        }

匹配 http://www.asdah.com/~joe | ftp://ftp.asdah.co.uk:2828/asdah%20asdah.gif | https://asdah.gov/asdh-ah.as

Javascript现在有一个名为new URL()的URL构造函数。它允许您完全跳过REGEX。

/** * * The URL() constructor returns a newly created URL object representing * the URL defined by the parameters. * * https://developer.mozilla.org/en-US/docs/Web/API/URL/URL * */ let requestUrl = new URL('https://username:password@developer.mozilla.org:8080/en-US/docs/search.html?par1=abc&par2=123&par3=true#Recent'); let urlParts = { origin: requestUrl.origin, href: requestUrl.href, protocol: requestUrl.protocol, username: requestUrl.username, password: requestUrl.password, host: requestUrl.host, hostname: requestUrl.hostname, port: requestUrl.port, pathname: requestUrl.pathname, search: requestUrl.search, searchParams: { par1: String(requestUrl.searchParams.get('par1')), par2: Number(requestUrl.searchParams.get('par2')), par3: Boolean(requestUrl.searchParams.get('par3')), }, hash: requestUrl.hash }; console.log(urlParts);

我想我找到了一个更通用的regexp来验证url,特别是网站

​(https?:\/\/)?(www\.)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)|(https?:\/\/)?(www\.)?(?!ww)[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)

它不允许例如www.something或http://www或http://www.something

点击这里查看:http://regexr.com/3e4a2

下面的正则表达式适用于我:

(http(s)?:\/\/.)?(ftp(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{0,256}\.[a-z] 
{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)

匹配:

https://google.com t.me https://t.me ftp://google.com http://sm.tj http://bro.tj t.me/rshss https:google.com www.cool.com.au http://www.cool.com.au http://www.cool.com.au/ersdfs http://www.cool.com.au/ersdfs?dfd=dfgd@s=1 http://www.cool.com:81/index.html

改进的

检测像这样的url:

https://www.example.pl http://www.example.com www.example.pl example.com http://blog.example.com http://www.example.com/product http://www.example.com/products?id=1&page=2 http://www.example.com#up http://255.255.255.255 255.255.255.255 http:// www.site.com: 8008

正则表达式:

/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/gm