Python匹配字符串,前缀不是X
我想在我的电脑上搜索一个叫“AcroTray.exe”的文件。如果这个文件不在“Distillr”这个文件夹里,程序应该给我发个警告。为此,我用了以下的语法来进行排除匹配。
(?!Distillr)
问题是,虽然我用了“!”这个符号,但它总是显示匹配成功。我试着用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
4 个回答
0
你正在尝试使用负向前查找:(?<!Distillr)\\AcroTray\.exe
0
你想要的是查看之前的内容,而不是往前看。就像这样:
(?<!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