python - Python正则表达式:如果字母不是列表中单词的一部分,则替换它
问题描述
假设我有一个单词列表,如果该字母不在单词列表中 [cat,hat,mat,ate]
,我想删除a
字符串中的所有字母。acatbatmate
catbtmate
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 演示。
如果您使用的是 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
Group 1 中,如果匹配,我们需要替换为该组内容。否则,我们要么替换为空字符串,要么替换为必需的替换。
请参阅正则表达式演示。
推荐阅读
- java - 从给定的 int 数组中形成最大数的正确代码是什么?
- python - 如何根据部分字符串匹配添加熊猫列?
- three.js - 如何创建一个用于放大三个js的滑块?我需要改变哪个参数?
- python - 关系/时间序列数据库和非常大的 SELECT 查询
- reactjs - 检查 Google 用户是否已存在于 firebase-react 应用程序中
- python-3.x - 如何获取网站文件夹中的文件列表?
- php - TINYTEXT 作为 MySQL 中的主键?
- php - 功能“get_header”在某些页面中不起作用
- javascript - 重新加载页面时多次调用 ComponentDidMount
- android - 我怎样才能画出这个形状?