[英]Replace all occurrences of 'pattern' in part of a string using Python regex
我想将苹果和橙色之间的所有“ <”符号替换为“-”。
>>> print re.sub(r'(apple.*)<(.*orange)', r'\1-\2', r'apple < < orange')
苹果<-橙
>>> print re.sub(r'(apple.*)<(?=.*orange)', r'\g<1>-', r'apple < < orange')
苹果<-橙
一次re.sub
调用仅处理非重叠匹配。
解决该问题的一种方法是蛮力:
>>> s = 'apple < < orange'
>>> old = None
>>> while s != old:
... old = s
... s = re.sub(r'(apple.*)<(.*orange)', r'\1-\2', s)
...
>>> print s
apple - - orange
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.