【问题标题】:Python match string if it does not start with X如果它不以 X 开头,则 Python 匹配字符串
【发布时间】:2013-03-10 04:15:45
【问题描述】:

我想在我的磁盘上搜索一个名为“AcroTray.exe”的文件。 如果文件位于“Distillr”以外的目录中,程序应打印警告。 我使用以下语法来执行否定匹配

(?!Distillr)

问题是虽然我使用了“!”它总是产生 MATCH。我尝试使用 IPython 找出问题,但失败了。 这是我尝试过的:

import re

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

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

它打印一个 MATCH。 我的正则表达式有什么问题?

我想参加比赛:

C:\SomeDir\AcroTray.exe

但不在:

C:\Distillr\AcroTray.exe

【问题讨论】:

    标签: python regex match


    【解决方案1】:

    使用否定的lookbehind ((?<!...)),而不是否定的lookahead:

    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
    

    【讨论】:

    • 哈。该死。我不得不扩展正则表达式,因为该文件可能位于两个目录中。 if re.search(r'(?&lt;!Distillr|!Acrobat)\\AcroTray\.exe', filePath): 但这需要一个固定的,我不能给出。
    • 啊——明白了。如果我使用两个表达式,则第二个必须比第一个短。 (?&lt;!Acrobat|!Distillr) 因“固定宽度”错误而失败。 (?&lt;!Distillr|!Acrobat) 工作正常。
    【解决方案2】:

    您正在尝试使用负面的后视:(?&lt;!Distillr)\\AcroTray\.exe

    【讨论】:

      【解决方案3】:

      您想要向后看,而不是向前看。像这样:

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

      【讨论】:

        【解决方案4】:

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

        看了你提供的例子,我以他们为例子here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-22
          • 2021-04-17
          • 2018-02-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多