2013-03-20 144 views
5

我想在我的磁盤上搜索名爲「AcroTray.exe」的文件。如果文件位於「Distillr」以外的目錄中,該程序應打印警告。 我用下面的語法來執行負匹配Python匹配字符串,如果它不以X開頭

(?!Distillr) 

的問題是,雖然我使用了「!」它總是產生一個MATCH。我試圖找出使用IPython的問題,但失敗了。 這就是我試過的:

import re 

filePath = "C:\Distillr\AcroTray.exe" 

if re.search(r'(?!Distillr)\\AcroTray\.exe', filePath): 
    print "MATCH" 

它打印一個匹配。 我的正則表達式有什麼問題?

我想獲得一個比賽上:

C:\SomeDir\AcroTray.exe 

但不是:

C:\Distillr\AcroTray.exe 

回答

1

使用負回顧後(?<!...)),不排除模式:

if re.search(r'(?<!Distillr)\\AcroTray\.exe', filePath): 

這符合:

In [45]: re.search(r'(?<!Distillr)\\AcroTray\.exe', r'C:\SomeDir\AcroTray.exe') 
Out[45]: <_sre.SRE_Match at 0xb57f448> 

此不匹配:

In [46]: re.search(r'(?<!Distillr)\\AcroTray\.exe', r'C:\Distillr\AcroTray.exe') 
# None 
+0

真棒!非常感謝... – JohnGalt 2013-03-20 20:44:49

+0

哈。該死的。 我不得不擴展正則表達式,因爲該文件可能位於兩個目錄中。 '如果re.search(r'(?<!Distillr |!Acrobat)\\ AcroTray \ .exe',filePath):' 但這需要一個固定的,我不能給。 – JohnGalt 2013-03-21 10:12:59

+0

它似乎在Ruby中工作 - [例子](http://rubular.com/r/zMfbJnCQuT) – JohnGalt 2013-03-21 10:25:46

0

您正在嘗試使用負向後看:(?<!Distillr)\\AcroTray\.exe

+0

非常感謝您的幫助 – JohnGalt 2013-03-20 20:55:24

0

你想看看背後,而不是展望。就像這樣:

(?<!Distillr)\\AcroTray\.exe 
0

(?mx)^((?!Distillr).)*$

看着你提供的例子,我把它們作爲例子here

相關問題