Regex to find A and not B on a line

点点圈 提交于 2019-12-22 07:01:16

问题


I'm looking for a regex to search my python program to find all lines where foo, but not bar, is passed into a method as a keyword argument. I'm playing around with lookahead and lookbehind assertions, but not having much luck.

Any help?

Thanks


回答1:


If you have a string foo that you want to find and another string bar that must not be present, you can use this:

^(?!.*bar).*foo

Creating a regular expression that exactly meets all your requirements is very difficult as Python code is not a regular language, but hopefully you should be able to use this as a starting point to get something good enough for your needs.




回答2:


Having the ^ after the lookaheads in these scenarios always seems to work better for me. Reading it makes more sense to me, too.

(?!.*bar)^.*foo

this has a foo          # pass
so does this has a foo  # pass
i can haz foo           # pass
but i haz foo and bar!  # fail



回答3:


You could also do this with not a regex:

for line in file:
    if "foo" in line and "bar" not in line:
        #do something


来源:https://stackoverflow.com/questions/2610581/regex-to-find-a-and-not-b-on-a-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!