我正在处理一个公交系统的大量大写站点名称,并希望将诸如"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'这个解决方案显然并不理想,因为我更希望有一个“纯”正则表达式解决方案。
发布于 2017-05-09 09:08:19
您可以用一个正的看台替换负的\w,用\W来更改
(?i)(?<=\W)the(?!\w)
^^^^^^^(?<!\w)的负查找可以表示为(?<=^|\W) (在Python中不起作用),我们只需要将^替代方案去掉。(?<=\W)正向后视要求在t的左侧立即使用一个非字字符。见regex演示。
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 Goethehttps://stackoverflow.com/questions/43865614
复制相似问题