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

2024-04-27 02:44:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个公交系统处理一大堆大写不好的站名,并想将“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'

这种解决方法显然不理想,因为我更喜欢一个“纯”regex解决方案。你知道吗


Tags: oftheto实例方法rethemeat
1条回答
网友
1楼 · 发布于 2024-04-27 02:44:29

您可以将负的lookback替换为正的lookback,将\w更改为\W

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

(?<!\w)负lookback可以表示为(?<=^|\W)(顺便说一句,在Python中不起作用),我们只需要从中去掉^替代方法。(?<=\W)正向lookback需要紧靠t左侧的非单词字符。参见regex demo。你知道吗

Python demo

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

相关问题 更多 >