I want to search for a file called "AcroTray.exe" on my disk. The program should print a warning if the file is located in a directory other than "Distillr". I used the following Syntax to perform the negative match
(?!Distillr)
The problem is that although I use the "!" it always produces a MATCH. I tried to figure out the problem using IPython but failed. This is what I tried:
import re
filePath = "C:\Distillr\AcroTray.exe"
if re.search(r'(?!Distillr)\\AcroTray\.exe', filePath):
print "MATCH"
It prints a MATCH. What is wrong with my regex?
I would like to get a match on:
C:\SomeDir\AcroTray.exe
But not on:
C:\Distillr\AcroTray.exe
Use negative lookbehind ((?<!...)
), not negative lookahead:
if re.search(r'(?<!Distillr)\\AcroTray\.exe', filePath):
This matches:
In [45]: re.search(r'(?<!Distillr)\\AcroTray\.exe', r'C:\SomeDir\AcroTray.exe')
Out[45]: <_sre.SRE_Match at 0xb57f448>
This does not match:
In [46]: re.search(r'(?<!Distillr)\\AcroTray\.exe', r'C:\Distillr\AcroTray.exe')
# None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With