URL验证正则表达式允许我想要禁止的一个案例

时间:2011-07-18 17:16:43

标签: regex regex-negation

这是我的正则表达式:

^(?#Protocol)((ht)tp(s?)\:\/\/|~\/|\/){1}((?#IP Address)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(?#Subdomains)(([-\w]+\.)+(?#TopLevel Domains))([a-z]+))(?#Port)(:[\d]{1,5})?(\/\S*)*$

它允许此网址,但我希望它禁止使用http://10.10.10.10.comasdf

任何人都可以帮我理解它的错误吗?

BTW, the following URLs are (correctly) allowed by the regex:

http://www.google.com
http://google.com
http://www.google.COM
http://google.co
http://www.google.c
http://www.google.biz
http://www.google.edu
http://android.google.com
http://www.google.com.asdf
http://android.google.com.jp
http://www.google.michael
http://www.mysite10.com
http://10mysite.com
http://209.85.148.103
http://209.85.148.103:8080
http://www.google.com:8080
http://www.google.japan
http://209.85.148.103/asdf
http://www.google.japan/asdf
http://www.google.japan/asdf/xcvb
http://209.85.148.103/asdf/xcvb
http://www.google.japan/asdf10/xcvb
http://209.85.148.103/asdf10/xcvb
http://www.google.japan/asdf10/xcvb30grts
http://209.85.148.103/asdf10/xcvb30grts
http://209.85.148.103/asdf10#xcvb30grts
http://www.google.japan/asdf10#xcvb30grts

1 个答案:

答案 0 :(得分:0)

当您的IP地址不匹配时,它会尝试匹配|条件。它成功完成,因为10.10.10.10.comasdf匹配([-\w]+\.)+([a-z]+)

尝试在?>之前加(?#IP Address)。这样,当ip地址匹配时,在|(?#Subdomains)(([-\w]+\.)+(?#TopLevel Domains))([a-z]+)

失败后,它不会尝试(?#Port)(:[\d]{1,5})?(\/\S*)*$
^(?#Protocol)((ht)tp(s?)\:\/\/|~\/|\/){1}(?>(?#IP Address)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(?#Subdomains)(([-\w]+\.)+(?#TopLevel Domains))([a-z]+))(?#Port)(:[\d]{1,5})?(\/\S*)*$

请参阅:http://regexr.com?2u8ks