Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python match string if it does not start with X

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
like image 850
JohnGalt Avatar asked Nov 12 '22 09:11

JohnGalt


1 Answers

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
like image 86
unutbu Avatar answered Nov 14 '22 23:11

unutbu