Joh*_*alt 2 python regex pattern-matching negative-lookbehind
我试图找出一个匹配文件路径字符串的正则表达式模式,其中名为"cmd.exe"的文件不在"System32"文件夹或其任何子文件夹中.
模式应与此匹配:
C:\Tools\calc.exe
但不是这个:
C:\Windows\System32\calc.exe
C:\Windows\System32\De-de\calc.exe
我尝试了背后的负面看法:
(?<![Ss]ystem32)\\calc\.exe
(?<![Ss]ystem32).*\\calc\.exe
(?<![Ss]ystem32[.*])\\calc\.exe
但迄今为止没有任何工作.有人看到我的错误吗?
您可以在此处查看我的示例并自行尝试:http: //rubular.com/r/syAoEn7xxx
谢谢你的帮助.
要回答问题的正则表达式问题,问题是re不支持可变长度的lookbehinds:
rx = r'(?<!System32.*)calc.exe'
re.search(rx, r'C:\Tools\calc.exe')
> sre_constants.error: look-behind requires fixed-width pattern
有两种解决方法:
安装并使用支持该功能的更新的正则表达式模块(以及更多):
rx = r'(?<!System32.*)calc.exe'
print regex.search(rx, r'C:\Tools\calc.exe')  # <_regex.Match object at 0x1028dd238>
print regex.search(rx, r'C:\Windows\System32\calc.exe') # None
或者重新表达表达式,使其不需要变量lookbehind:
rx = r'^(?!.*System32).*calc.exe'
print re.search(rx, r'C:\Tools\calc.exe')  # <_sre.SRE_Match object at 0x10aede238>
print re.search(rx, r'C:\Windows\System32\calc.exe') # None
| 归档时间: | 
 | 
| 查看次数: | 281 次 | 
| 最近记录: |