[英]python regex match A but not B in any order
這個問題在這里有答案,但我似乎無法將它應用到我的用例中。
我想匹配一個包含單詞“reset”但不包含密碼的字符串。 例如假設我有以下兩個:
queries = ["reset my password", "reset my account please.", "password reset"]
for q in queries:
print(is_reset(q))
should output False, True, False
其中is_reset
將包含正則表達式。
我試過的正則表達式是:
matches = re.search("(?=reset)(?!.*password)", text)
if matches:
print("Matched")
else:
print("No match")
上面的最后一個查詢似乎有問題。 我也在盲目地復制正則表達式,有人可以解釋上面的正則表達式/答案是什么意思嗎?
您當前模式(?=reset)(?..*password)
的主要問題是,雖然它確實具有前瞻性斷言存在reset
且password
不存在,但模式本身的寬度為零,因此永遠不會匹配任何非零寬度的內容。 我會使用這種模式:
^(?!.*\bpassword\b).*\breset\b.*$
這與在任何地方出現reset
的任何輸入相匹配,並且它在開始時有一個否定斷言以排除password
存在。
示例腳本:
queries = ["reset my password", "reset my account please.", "password reset"]
for q in queries:
matches = re.search(r'^(?!.*\bpassword\b).*\breset\b.*$', q)
if matches:
print("Matched: " + q)
else:
print("No match: " + q)
這打印:
No match: reset my password
Matched: reset my account please.
No match: password reset
如果您想使用正則表達式執行此操作,則必須對passsword
進行否定查找並在reset
時進行肯定查找 -
^(?=.*reset)(?..*password).*
這應該工作。
(?=.*reset)
-> 有reset
時匹配。 (?..*password).*
-> 有password
時不匹配
主要問題是你總是期望重置之前沒有任何東西。 在reset
之前添加一個.*
以指示它之前也可以有字符。 同樣, password
后面也可以有字符。 因此.*
password
后
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.