简体   繁体   English

python 正则表达式以任何顺序匹配 A 但不匹配 B

[英]python regex match A but not B in any order

This question has an answer here but I can't seem to be able to adopt it to my use case.这个问题在这里有答案,但我似乎无法将它应用到我的用例中。

I want to match to a string that contains the word "reset" but not password.我想匹配一个包含单词“reset”但不包含密码的字符串。 For example suppose I have the following two:例如假设我有以下两个:

queries = ["reset my password", "reset my account please.", "password reset"]
for q in queries:
    print(is_reset(q))

should output False, True, False where is_reset would contain the regex. should output False, True, False其中is_reset将包含正则表达式。

The regex that I tried was:我试过的正则表达式是:

matches = re.search("(?=reset)(?!.*password)", text)
if matches:
    print("Matched")
else:
    print("No match")

The above seems to have an issue with the last query.上面的最后一个查询似乎有问题。 Also I am blindly copying the regex, couls someone explain what the regex above/ answer means?我也在盲目地复制正则表达式,有人可以解释上面的正则表达式/答案是什么意思吗?

The main problem with your current pattern (?=reset)(?..*password) is that while it does correctly have lookaheads which assert that reset is present and password is not present, the pattern itself is zero width, and so will never match any content which is not zero width.您当前模式(?=reset)(?..*password)的主要问题是,虽然它确实具有前瞻性断言存在resetpassword存在,但模式本身的宽度为零,因此永远不会匹配任何非零宽度的内容。 I would use this pattern:我会使用这种模式:

^(?!.*\bpassword\b).*\breset\b.*$

This matches any input with reset appearing anywhere, and it has a negative assertion at the beginning to exclude password from being present.这与在任何地方出现reset的任何输入相匹配,并且它在开始时有一个否定断言以排除password存在。

Sample script:示例脚本:

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)

This prints:这打印:

No match: reset my password
Matched:  reset my account please.
No match: password reset

If you want to do this with regex, you have to a negative lookup on passsword and positive lookup on reset -如果您想使用正则表达式执行此操作,则必须对passsword进行否定查找并在reset时进行肯定查找 -

^(?=.*reset)(?..*password).*

This should work.这应该工作。

(?=.*reset) -> Matches when there is reset . (?=.*reset) -> 有reset时匹配。 (?..*password).* -> Dont match when there is password (?..*password).* -> 有password时不匹配

The main problem was you were always expecting reset to be not have anything before it.主要问题是你总是期望重置之前没有任何东西。 add a .* before reset to indicate it can have characters before it as well.reset之前添加一个.*以指示它之前也可以有字符。 Similarly password can have charcters after it as well.同样, password后面也可以有字符。 hence the .* after password因此.* password

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM