12

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

Zach
  • 18,594
  • 18
  • 59
  • 68

4 Answers4

15

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • I'm fairly confident all the occurrences are on the same line, and if I miss some it doesn't matter. I just mentioned python to give some context. – Zach Apr 09 '10 at 20:23
  • @Zach, what Mark meant is that the string `bar` could occur without being a keyword (or did you mean identifier?): it could be inside a string literal or part of a comment. – Bart Kiers Apr 09 '10 at 20:26
5

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
maček
  • 76,434
  • 37
  • 167
  • 198
  • 1
    Could you post a string that works "better" when placing the `^` after it instead of before? – Bart Kiers Apr 09 '10 at 20:24
  • 1
    Big props for this, python regex frustrating solved. Was trying to find all files of a certain name but exclude any tilde backup files. (?!.*~)^.*filename.ext – Halsafar Jun 18 '15 at 18:48
1

You could also do this with not a regex:

for line in file:
    if "foo" in line and "bar" not in line:
        #do something
Ipsquiggle
  • 1,814
  • 1
  • 15
  • 25
  • I'm searching through many files so it's much easier to just use a tool that takes a regular expression and handles the traversing of files for me. Thanks though – Zach Apr 09 '10 at 20:47
  • For sure. I love regexes and use them daily. It's just worth bearing in mind that sometimes, you should just tell the program exactly what you want and save yourself a headache. ;) – Ipsquiggle Apr 16 '10 at 15:49
0

Match whole line:

^(?=.*a)(?!.*b).*$