2013-03-20 135 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

相关问题