Regexp匹配除外
我试图通过regexp匹配一些路径,但不匹配其他路径。我希望匹配以“/profile/”开头的任何内容,这些内容不是以下内容之一:Regexp匹配除外,regex,Regex,我试图通过regexp匹配一些路径,但不匹配其他路径。我希望匹配以“/profile/”开头的任何内容,这些内容不是以下内容之一: /配置文件/属性 /简介/论文 /配置文件/编辑 下面是我尝试使用的正则表达式,它似乎不起作用: ^/profile/(?!attributes|essays|edit)$ 例如,这些URL中没有一个与上述URL正确匹配: /轮廓/亚光 /个人资料/127 /个人资料/-591m!40v81,ma/asdf?foo=bar#第1页 您需要说,在字符串结束之前
- /配置文件/属性
- /简介/论文
- /配置文件/编辑
^/profile/(?!attributes|essays|edit)$
例如,这些URL中没有一个与上述URL正确匹配:
- /轮廓/亚光
- /个人资料/127
- /个人资料/-591m!40v81,ma/asdf?foo=bar#第1页
^/profile/(?!attributes|essays|edit).*$
移除管柱端锚也可以:
^/profile/(?!attributes|essays|edit)
而且,您可能希望在负面展望中更加严格,以避免排除/profile/editor
:
^/profile/(?!(?:attributes|essays|edit)$)
注释很难读懂代码,所以这里是我的答案,格式很好
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 ''
相信你忘记了你的。*在点击EOL之前先把剩下的部分细细咀嚼一遍,
/profile/attributes?x=1
,/profile/attributes/foo
,/profile/attributes./profile/attributes>,/profile//attributes
,/profile///attributes
,/profile/。
?是否匹配?^/profile/(?!(?:属性|文章|编辑)$)应更改为:^/profile/(?!(?:属性|文章|编辑)).$。。。否则,您将匹配后面有其他内容的路径,例如/profile/articles/hello|u world.txt要考虑像您提到的编辑器这样的内容,可能还需要验证($|/):::^/profile/(?!(?)(?:attributes | articles | edit)($|/)在这种情况下,它可以吸收任何内容,直到命中($|/)对吗?:::>>m=re.compile(“^/profile/(?!(?:attributes | assets | edit)。*?($|/)”>>>m.search('/profile/assets/hello_world.txt')>>m.search('/profile/esssysd/hello_world.txt'))代码有点混乱。基本上你得到的是^/profile/(?!(?:属性|文章|编辑)($|/).$
,这对我个人来说更容易阅读。投票支持regex。