假设我有一个像 [cat,hat,mat,ate] 这样的单词列表,我想删除像 这样的字符串中的所有字母 到 a >acatbatmatecatbtmate 如果字母 a 不在单词列表中。
在当前步骤中,我可以使用以下代码按单词列表中的单词拆分字符串:
''.join([word.replace('a','')
if word not in ['cat','hat','mat','ate']
else word for word in re.split('(cat|hat|mat|ate)','acatbatmate') ])
我可以使用 re.sub(pattern, repl, string) 直接删除字母 a 吗?
请您参考如下方法:
你可以像这样使用 re 轻松地做到这一点:
import re
except_contexts = ['cat','hat','mat','ate']
print(re.sub(r'({})|a'.format("|".join(except_contexts)), lambda x: x.group(1) if x.group(1) else '', 'acatbatmate'))
# => catbtmate
参见 Python 2 demo .
如果您使用的是 Python 3.5+,仅使用反向引用就更容易了:
import re
except_contexts = ['cat','hat','mat','ate']
print(re.sub(r'({})|a'.format("|".join(except_contexts)), r'\1', 'acatbatmate'))
但是,如果您打算替换 a,则需要使用 lambda 表达式。
详情
r'({})|a'.format("|".join(except_contexts)) 看起来像 (cat|hat|mat|ate)|a正则表达式。它会将cat、hat等匹配并捕获到第1组中,如果匹配,我们需要替换为该组内容。否则,我们要么替换为空字符串,要么替换为所需的替换。
参见 regex demo .
