替换除字符串开头之外的所有子字符串实例



我正在为交通系统处理大量大写不佳的车站名称,并希望将"at"和"the"等单词大写。到目前为止,我可以匹配我想要的所有实例,除了我无法弄清楚如何匹配字符串开头出现的实例。(即防止将"事物"更改为"事物")

这是我到目前为止的代码:

>>>re.sub("(?i)(?<!w)the(?!w)", "zzz", "The Thing To The Theme of Athens, (The) Goethe")
'zzz Thing To zzz Theme of Athens, (zzz) Goethe'

他是我目前的解决方法:

>>>re.sub("(?i)(?<![w|])the(?!w)", "zzz", "|" + "The Thing To The Theme of Athens, (The) Goethe")[1:]
'The Thing To zzz Theme of Athens, (zzz) Goethe'

这种解决方法显然并不理想,因为我更喜欢"纯粹"的正则表达式解决方案。

您可以将负面的回溯替换为正面的,将w替换为W

(?i)(?<=W)the(?!w)
^^^^^^^

(?<!w)负面的回溯可以表示为(?<=^|W)(在 Python 中不起作用,顺便说一句),我们只需要从中取出^替代方案。(?<=W)正面的回望需要紧靠t左侧的非单词字符。请参阅正则表达式演示。

蟒蛇演示:

import re
res = re.sub(r"(?i)(?<=W)the(?!w)", "zzz", "The Thing To (The) Theme of Athens, The Goethe")
print(res) # => The Thing To (zzz) Theme of Athens, zzz Goethe

最新更新