首页 > 解决方案 > Python查找所有出现的连字符并替换位置

问题描述

我必须用最后一个标记(即或在本例中)用连字符(如c-c-c-c-comeoroh-oh-oh-oh等​​)替换所有出现的模式,其中comeoh

[更新]

假设这些连字符不属于固定字典,我将添加此约束:

标签: pythonregex

解决方案


您可以只使用re.sub()来替换所有,而不必遍历匹配的索引:

import re

s = 'c-c-c-c-come to home today c-c-c-c-come to me'

print(re.sub(r'(\w+(?:-))+(\w+)', '\\2', s))
# come to home today come to me

推荐阅读