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

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


当前回答

我认为有些人无法使用您的php代码,因为其中隐含的修饰符。我复制了你的代码作为一个例子:

if(
    preg_match(
        "/^{$IRI_reference}$/iu",
        'http://www.url.com'
    )
){
    echo 'true';
}

注意“i”和“u”修饰语。如果没有“u”,PHP会抛出一个异常:

Warning: preg_match() [function.preg-match]: Compilation failed: character value in \x{...} sequence is too large at offset XX

其他回答

非验证uri引用解析器

为了便于参考,这里是IETF规范:(TXT | HTML)。特别地,附录b用正则表达式解析URI引用演示了如何解析有效的正则表达式。这被描述为,

这是一个非验证URI引用解析器的例子,它将接受任何给定的字符串并提取URI组件。

下面是它们提供的正则表达式:

 ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?

正如其他人所说,最好将此留给您已经在使用的库/框架。

要将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。

这可能不是正则表达式的工作,而是您所选语言中的现有工具的工作。您可能希望使用已经编写、测试和调试过的现有代码。

在PHP中,使用parse_url函数。

URI模块。

Ruby: URI模块。

.NET: 'Uri'类

正则表达式并不是你在每个涉及字符串的问题上挥舞的魔杖。

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