是否有一个正则表达式来查找,例如 ">ab"
但不在结果中包含 ">"
?
我想用 re.sub
替换一些字符串,我想找到以 ">"
开头的字符串而不删除 ">"
.
最佳答案
您需要一个积极的回顾断言。参见 the docs .
r'(?<=>)ab'
它需要是一个固定长度的表达式,它不能是可变数量的字符。基本上,做
r'(?<=stringiwanttobebeforethematch)stringiwanttomatch'
举个例子:
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')
关于Python:查找但不包含字母数字的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7030584/