Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式:如果字母不是列表中单词的一部分,则替换它_Python_Regex_Python 3.x - Fatal编程技术网

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
to
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

是的,你可以(我一直想这样写……):

这利用了较新的
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'))