微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么这个正则表达式前瞻不起作用?

我正在设计一个在一些IIS Url重写中使用的正则表达式.目的是捕获以下网址:

>不仅仅是根目录中的文件(通过包含句点标识),以及
>不要包含查询字符串,并且
>不属于特定的子目录集,特别是“帐户”和“公共”

我目前的正则表达式如下:

^(?!(Account)|(Public))([^./]+)(/[^?]*)?$

使用RegexPal测试集:

file.aspx
Account/otherfile.aspx
Public/otherfile.aspx
otherfolder1/otherfile.aspx?stuff=otherstuff
otherfolder2/otherfolder/otherfile.aspx
otherfolder3/
otherfolder4

我的正则表达式正确地忽略了前两种情况,但它仍然匹配第三种情况.前瞻有什么问题?

解决方法

我无法抗拒试图提出一些可以在RegExPal中工作的东西(没有成功 – 编辑:刚刚验证过,这确实在RegExPal中有效)但是我想我会把它作为另一种方式来做你需要的东西,这可能更容易理解:

^(?!Account|Public|[a-zA-Z_0-9]+\.)[a-zA-Z_0-9/.]+$

解释:

^                   # start
(?!                 # open a negative lookahead
Account|Public|     # ignore both Account and Public
[a-zA-Z_0-9]+\.     # ignore files in root (i.e.,letters/numbers,followed by period)
)                   # close negative lookahead
[a-zA-Z_0-9/.]+     # Now match anything with letters/numbers,periods and slashes,but no '?' (ignores URLs with query string)
$                  # end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐