2011-09-27 110 views
2

我想匹配一些路径,但不是通过正则表达式匹配其他路径。我想匹配任何开头 “/型材/” 那不是下列之一:正则表达式匹配除了

  • /资料/属性
  • /资料/随笔
  • /型材/编辑

这里是我尝试使用似乎并没有被工作正则表达式:

^/profile/(?!attributes|essays|edit)$ 

例如,没有这些URL的正确配套配件克以上!?

  • /资料/亚光
  • /型材/ 127
  • /型材/ -591m 40v81,MA /航空自卫队富=酒吧#1页
+0

相信你忘了你的*。在命中之前嚼剩下的线 – pyInTheSky

+1

'/ profile/attributes?x = 1','/ profile/attributes/foo','/ profile/attributes#bar ','/ profile/attributes2','/ profile/。/ attributes','/ profile // attributes','/ profile/..'?他们应该匹配还是不匹配? –

回答

4

您需要说,可以有任意字符,直到字符串的结尾:

^/profile/(?!attributes|essays|edit).*$ 

删除结束串锚也将工作:

^/profile/(?!attributes|essays|edit) 

而且你可能想在你的负面先行更为严格,以避免不包括/profile/editor

^/profile/(?!(?:attributes|essays|edit)$) 
+0

^/profile /(?!(?: attributes | essays | edit)$) 应改为:^/profile /(?!(?: attributes | essays | edit))。* $ ...否则你会匹配具有其他内容的路径,例如/profile/essays/hello_world.txt – pyInTheSky

+1

需要考虑像您提到的编辑器之类的内容,也许还要验证($ | /)::: ^/profile/(?!(?:attributes | essays | edit)($ | /)) – pyInTheSky

+0

@pyInTheSky,'/ profile/attributes#bar'? –

1

评论是难以阅读的代码,所以这里是我的漂亮的格式回答

def mpath(path, ignore_str = 'attributes|essays|edit',anything = True): 
    any = '' 
    if anything: 
     any = '.*?' 
    m = re.compile("^/profile/(?!(?:%s)%s($|/)).*$" % (ignore_str,any)) 
    match = m.search(path) 
    if match: 
     return match.group(0) 
    else: 
     return '' 
+0

代码有点令人困惑。基本上,你得到的是'^/profile /(?!(?:attributes | essays | edit)($ | /)).*$',这对我来说更容易阅读。 Upvote为正则表达式。 –