2017-05-09 109 views
2

我正在处理一系列运输系统的大写字母数量不足的站点名称,并且希望删除“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' 

这种解决方法显然是不理想的,因为我宁愿有一个“纯粹”的正则表达式解决方案。

回答

2

您可以用积极的变化更换负回顾后\w\W

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

(?<!\w)负回顾后可以作为(?<=^|\W)(在Python不工作,BTW),我们只需要把^替代它。 (?<=\W)肯定看后面的要求立即在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 
+1

那是快。谢谢! – Zoetrophy