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

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


当前回答

我用这个:/ ((https ?: \ / \ / | ftp: \ / \ / | www \) \ S + \[^。\ n ]+((?:\([^)]*\))|[^.,;:?!"'\ n \)\]<* ])+)/

它很短,但它处理了一些边缘情况,比如某些以括号结尾的维基百科链接(https://en.wikipedia.org/wiki/Sally_(name),这里投票最多的答案似乎没有涵盖这一点。

其他回答

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);

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

(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

我想我找到了一个更通用的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

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\-\._\?\,\'/\\\+&amp;%\$#\=~])*$");
            return urlregex.test(textval);
        }

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

https?:\/{2}(?:[\/-\w.]|(?:%[\da-fA-F]{2}))+

您可以使用此模式来检测url。

下面是概念的证明

RegExr: URL检测器