我正在为公交系统处理一大堆大写不当的车站名称,并希望将“at”和“the”等词取消大写。到目前为止,我可以匹配所有我想要的实例,除了我不知道如何不匹配出现在字符串开头的实例。 (即防止将“The Thing”更改为“The Thing”)
到目前为止,这是我的代码:
>>>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 的积极的 lookbehind 来代替消极的 lookbehind与 \W :
(?i)(?<=\W)the(?!\w)
^^^^^^^
(?<!\w)负面回顾可以表示为 (?<=^|\W) (不能在 Python 中工作,顺便说一句),我们只需要获取 ^替代它。 (?<=\W)正向后视需要紧靠t 左侧的非单词字符.查看regex 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
