Python匹配字符串,如果它不以X开头
问题描述:
我想在我的磁盘上搜索名为“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
答
使用负回顾后((?<!...)
),不排除模式:
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
答
你想看看背后,而不是展望。就像这样:
(?<!Distillr)\\AcroTray\.exe
真棒!非常感谢... – JohnGalt 2013-03-20 20:44:49
哈。该死的。 我不得不扩展正则表达式,因为该文件可能位于两个目录中。 '如果re.search(r'(? JohnGalt 2013-03-21 10:12:59
它似乎在Ruby中工作 - [例子](http://rubular.com/r/zMfbJnCQuT) – JohnGalt 2013-03-21 10:25:46