Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to find A and not B on a line

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

like image 717
Zach Avatar asked Apr 09 '10 20:04

Zach


2 Answers

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
like image 56
maček Avatar answered Oct 18 '22 04:10

maček


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.

like image 24
Mark Byers Avatar answered Oct 18 '22 05:10

Mark Byers