简短的版本是您不能在使用 Python 的 re 模块的后视中使用可变宽度模式。没有办法改变这一点:
>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
re.sub("(?<=fo+)bar(?=baz)", "quux", string)
File "C:\Development\Python25\lib\re.py", line 150, in sub
return _compile(pattern, 0).sub(repl, string, count)
File "C:\Development\Python25\lib\re.py", line 241, in _compile
raise error, v # invalid expression
error: look-behind requires fixed-width pattern
这意味着您需要解决它,最简单的解决方案与您现在正在做的非常相似:
>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)
这没有lookbehind 解决方案的优雅,但它仍然是一个非常清晰、直接的单行。如果你看一下 an expert has to say on the matter 的内容(他说的是 JavaScript,它完全缺乏后视功能,但许多原理都是相同的),你会发现他最简单的解决方案看起来很像这个。