你想要一个积极的lookbehind断言.查看文档.
r'(?<=>)ab'
Run Code Online (Sandbox Code Playgroud)
它需要是一个固定长度的表达式,它不能是可变数量的字符.基本上,做
r'(?<=stringiwanttobebeforethematch)stringiwanttomatch'
Run Code Online (Sandbox Code Playgroud)
那么,一个例子:
import re
# replace 'ab' with 'e' if it has '>' before it
#here we've got '>ab' so we'll get '>ecd'
print re.sub(r'(?<=>)ab', 'e', '>abcd')
#here we've got 'ab' but no '>' so we'll get 'abcd'
print re.sub(r'(?<=>)ab', 'e', 'abcd')
Run Code Online (Sandbox Code Playgroud)
您可以在sub中使用后向引用:
import re
test = """
>word
>word2
don't replace
"""
print re.sub('(>).*', r'\1replace!', test)
Run Code Online (Sandbox Code Playgroud)
输出:
>replace!
>replace!
don't replace
Run Code Online (Sandbox Code Playgroud)
我相信当你说"我想用一些字符串代替re.sub,并且我想找到以' >' 开头而不删除' >'的字符串时,这就完成了你真正想要的东西."