Python正则表达式:如果字母不是列表中单词的一部分,则替换它
假设我有一个单词列表,如Python正则表达式:如果字母不是列表中单词的一部分,则替换它,python,regex,python-3.x,Python,Regex,Python 3.x,假设我有一个单词列表,如[cat,hat,mat,ate],如果字母a不在单词列表中,我想删除acatbatmatetocatbtmate字符串中的所有字母a 在当前步骤中,我可以使用以下代码按单词列表中的单词拆分字符串: ''.join([word.replace('a','') if word not in ['cat','hat','mat','ate'] else word for word in re.split('(cat|hat|mat|at
[cat,hat,mat,ate]
,如果字母a
不在单词列表中,我想删除acatbatmate
tocatbtmate
字符串中的所有字母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
是的,你可以(我一直想这样写……):
这利用了较新的regex
模块,该模块支持(*跳过)(*失败)
这里的模式是:
(?:cat|hat|mat|ate)(*SKIP)(*FAIL)
|
a+
如果没有新模块,您可以使用函数
处理程序:
import re
exceptions = ['cat','hat','mat','ate']
def handler(match):
if match.group(1):
return ''
return match.group(0)
rx = re.compile(r'''(?:{})|(a+)'''.format('|'.join(exceptions)))
word = rx.sub(handler, 'acatbatmate')
print(word)
您可以使用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 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'。格式(“|”。.join(上下文除外))
将类似于(cat | hat | mat | ate)a
regex。它将匹配并将cat
、hat
等捕获到组1中,如果匹配,我们需要用该组内容替换。否则,我们要么替换为空字符串,要么替换为必需的字符串
请参阅。什么是Python版本?很抱歉,迟来的回复,它是Python 3.6,所以要删除,您可以使用需要PyPi正则表达式模块的注释。lambda x:x.group(1)如果x.group(1)其他“”
可以是lambda x:x.group(1)或“”
@Jean Françoisfare,这会稍微缩短代码。但是,my较短:),它将在Python3.6OP中工作。
import re
except_contexts = ['cat','hat','mat','ate']
print(re.sub(r'({})|a'.format("|".join(except_contexts)), r'\1', 'acatbatmate'))