首页 > 解决方案 > Python正则表达式:如果字母不是列表中单词的一部分,则替换它

问题描述

假设我有一个单词列表,如果该字母不在单词列表中 [cat,hat,mat,ate],我想删除a字符串中的所有字母。acatbatmatecatbtmatea

在当前步骤中,我可以使用以下代码按单词列表中的单词拆分字符串:

''.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吗?

标签: pythonregexpython-3.x

解决方案


您可以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 演示

如果您使用的是 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正则表达式。它将匹配并将 , 等捕获cathatGroup 1 中,如果匹配,我们需要替换为该组内容。否则,我们要么替换为空字符串,要么替换为必需的替换。

请参阅正则表达式演示


推荐阅读