如何检查给定的字符串是否是有效的URL地址?
我对正则表达式的知识是基本的,不允许我从我已经在网上看到的数百个正则表达式中进行选择。
如何检查给定的字符串是否是有效的URL地址?
我对正则表达式的知识是基本的,不允许我从我已经在网上看到的数百个正则表达式中进行选择。
当前回答
经过严格的搜索,我最终确定如下
^[a-zA-Z0-9]+\:\/\/[a-zA-Z0-9]+\.[-a-zA-Z0-9]+\.?[a-zA-Z0-9]+$|^[a-zA-Z0-9]+\.[-a-zA-Z0-9]+\.[a-zA-Z0-9]+$
这个在未来的url中也适用。
其他回答
我写了一个很棒的版本,你可以运行
它匹配以下url(这对我来说已经足够好了)
public static void main(args) {
String url = "go to http://www.m.abut.ly/abc its awesome"
url = url.replaceAll(/https?:\/\/w{0,3}\w*?\.(\w*?\.)?\w{2,3}\S*|www\.(\w*?\.)?\w*?\.\w{2,3}\S*|(\w*?\.)?\w*?\.\w{2,3}[\/\?]\S*/ , { it ->
"woof${it}woof"
})
println url
}
http://google.com
http://google.com/help.php
http://google.com/help.php?a=5
http://www.google.com
http://www.google.com/help.php
http://www.google.com?a=5
google.com?a=5
google.com/help.php
google.com/help.php?a=5
http://www.m.google.com/help.php?a=5 (and all its permutations)
www.m.google.com/help.php?a=5 (and all its permutations)
m.google.com/help.php?a=5 (and all its permutations)
对于任何不以http或www开头的url,重要的是它们必须包含/或?
我打赌这可以稍作调整,但它的工作非常好,因为它是如此简短和紧凑……因为你可以把它分成三份:
找到任何以http开头的内容:
https?:\/\/w{0,3}\w*?\.\w{2,3}\S*
找到任何以www开头的东西:
www\.\w*?\.\w{2,3}\S*
或者找到任何必须有一个文本,然后一个点,然后至少两个字母,然后一个?或/:
\w*?\.\w{2,3}[\/\?]\S*
下面是针对这种情况的最佳和最匹配的正则表达式
^(?:http(?:s)?:\/\/)?(?:www\.)?(?:[\w-]*)\.\w{2,}$
https?:\/{2}(?:[\/-\w.]|(?:%[\da-fA-F]{2}))+
您可以使用此模式来检测url。
下面是概念的证明
RegExr: URL检测器
对于Python,这是Django 1.5.1中使用的验证正则表达式的实际URL:
import re
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4
r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
这既处理ipv4和ipv6地址,也处理端口和GET参数。
在代码44行中找到。
我想我找到了一个更通用的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