((HTTPS | FTP):// | WWW)(\ S + [^ *])
我希望这个表达式能够检查。彼此相继。如果它背靠背找到两个或多个句点,则表达式应该失败。另一方面,如果成功,我希望它匹配每个字符和/或符号,直到遇到第一个空格。
换句话说: www.yahoo..com应该失败
在相关的说明中:我意识到这个表达式在判断有效的URL结构方面是非常基本的。我有另一个“更聪明”的正则表达式,它位于上面的那个之前。发布的目的是检查通过preg_match_all从初始正则表达式传递的URL的有效性。
答案 0 :(得分:3)
您可能希望使用http://php.net/manual/en/book.filter.php查看FILTER_VALIDATE_URL,而不是使用Regex来验证您的网址。
以下是示例用法:
$ url =“http://www.example.com”;
if(!filter_var($url, FILTER_VALIDATE_URL))
{
echo "URL is not valid";
}
else
{
echo "URL is valid";
}
答案 1 :(得分:0)
如果你的引擎支持它,使用负向前瞻是一种简单的方法:
(?!.*\.\.)((https?|ftp)\:\/\/|www.)(\S+[^.*])
否则,你必须更具体:
^((https?|ftp)\:\/\/|www.)((\.[^.]|[^.\s])+[^.*])($|\s+)
答案 2 :(得分:0)
您可以这样做:
((https?|ftp)\:\/\/|www.)((?:[\w\-]+\.)*[\w\-]+)
即使您跳过双点,也不会检查有效的网址。如果您使用的语言(PHP?)有其他验证URL的方法,我建议不要使用正则表达式。
RFC声明如下:
; URL schemeparts for ip based protocols:
ip-schemepart = "//" login [ "/" urlpath ]
login = [ user [ ":" password ] "@" ] hostport
hostport = host [ ":" port ]
host = hostname | hostnumber
hostname = *[ domainlabel "." ] toplabel
domainlabel = alphadigit | alphadigit *[ alphadigit | "-" ] alphadigit
toplabel = alpha | alpha *[ alphadigit | "-" ] alphadigit
alphadigit = alpha | digit
hostnumber = digits "." digits "." digits "." digits
port = digits
user = *[ uchar | ";" | "?" | "&" | "=" ]
password = *[ uchar | ";" | "?" | "&" | "=" ]
urlpath = *xchar ; depends on protocol see section 3.1
; HTTP
httpurl = "http://" hostport [ "/" hpath [ "?" search ]]
hpath = hsegment *[ "/" hsegment ]
hsegment = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
search = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
; Miscellaneous definitions
lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" |
"i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" |
"q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" |
"y" | "z"
hialpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
"J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
"S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
alpha = lowalpha | hialpha
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
"8" | "9"
safe = "$" | "-" | "_" | "." | "+"
extra = "!" | "*" | "'" | "(" | ")" | ","
national = "{" | "}" | "|" | "\" | "^" | "~" | "[" | "]" | "`"
punctuation = "<" | ">" | "#" | "%" | <">
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "="
hex = digit | "A" | "B" | "C" | "D" | "E" | "F" |
"a" | "b" | "c" | "d" | "e" | "f"
escape = "%" hex hex
unreserved = alpha | digit | safe | extra
uchar = unreserved | escape
xchar = unreserved | reserved | escape
digits = 1*digit