[英]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.