我想匹配一些路徑,但不是通過正則表達式匹配其他路徑。我想匹配任何開頭 「/型材/」 那不是下列之一:正則表達式匹配除了
- /資料/屬性
- /資料/隨筆
- /型材/編輯
這裏是我嘗試使用似乎並沒有被工作正則表達式:
^/profile/(?!attributes|essays|edit)$
例如,沒有這些URL的正確配套配件克以上!?
- /資料/亞光
- /型材/ 127
- /型材/ -591m 40v81,MA /航空自衛隊富=酒吧#1頁
我想匹配一些路徑,但不是通過正則表達式匹配其他路徑。我想匹配任何開頭 「/型材/」 那不是下列之一:正則表達式匹配除了
這裏是我嘗試使用似乎並沒有被工作正則表達式:
^/profile/(?!attributes|essays|edit)$
例如,沒有這些URL的正確配套配件克以上!?
您需要說,可以有任意字符,直到字符串的結尾:
^/profile/(?!attributes|essays|edit).*$
刪除結束串錨也將工作:
^/profile/(?!attributes|essays|edit)
而且你可能想在你的負面先行更爲嚴格,以避免不包括/profile/editor
:
^/profile/(?!(?:attributes|essays|edit)$)
^/profile /(?!(?: attributes | essays | edit)$) 應改爲:^/profile /(?!(?: attributes | essays | edit))。* $ ...否則你會匹配具有其他內容的路徑,例如/profile/essays/hello_world.txt – pyInTheSky
需要考慮像您提到的編輯器之類的內容,也許還要驗證($ | /)::: ^/profile/(?!(?:attributes | essays | edit)($ | /)) – pyInTheSky
@pyInTheSky,'/ profile/attributes#bar'? –
評論是難以閱讀的代碼,所以這裏是我的漂亮的格式回答
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 ''
代碼有點令人困惑。基本上,你得到的是'^/profile /(?!(?:attributes | essays | edit)($ | /)).*$',這對我來說更容易閱讀。 Upvote爲正則表達式。 –
相信你忘了你的*。在命中之前嚼剩下的線 – pyInTheSky
'/ profile/attributes?x = 1','/ profile/attributes/foo','/ profile/attributes#bar ','/ profile/attributes2','/ profile/。/ attributes','/ profile // attributes','/ profile/..'?他們應該匹配還是不匹配? –