Regex find A, not B on the line

I am looking for a regular expression to search in my python program to find all the lines where foo , but not bar , is passed to the method as a keyword argument. I play with statements and views, but I don't have much luck.

Any help?

thanks

+4
source share
3 answers

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

 ^(?!.*bar).*foo 

Creating a regular expression that exactly matches all your requirements is very difficult, because Python code is not a common language, but I hope you can use it as a starting point to get something good enough for your needs.

+5
source

Having ^ after the looks in these scenarios always seem better to me. Reading makes more sense to me.

(?!.*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 
+2
source

You can also do this without regex:

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

Source: https://habr.com/ru/post/1306517/


All Articles