Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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 使用以正则表达式为键的dict进行多个正则表达式替换_Python_Regex_String_Substitution_Re - Fatal编程技术网

Python 使用以正则表达式为键的dict进行多个正则表达式替换

Python 使用以正则表达式为键的dict进行多个正则表达式替换,python,regex,string,substitution,re,Python,Regex,String,Substitution,Re,我想使用多个正则表达式对字符串进行多次替换。我还希望在单个过程中进行替换,以避免创建字符串的多个实例 让我们假设我要进行以下替换,同时避免多次使用re.sub(),无论是显式使用还是循环使用: import re text = "local foals drink cola" text = re.sub("(?<=o)a", "w", text) text = re.sub("l(?=a)", "c

我想使用多个正则表达式对字符串进行多次替换。我还希望在单个过程中进行替换,以避免创建字符串的多个实例

让我们假设我要进行以下替换,同时避免多次使用re.sub(),无论是显式使用还是循环使用:

import re

text = "local foals drink cola"
text = re.sub("(?<=o)a", "w", text)
text = re.sub("l(?=a)", "co", text)

print(text) # "local fowls drink cocoa"
现在请注意,将所需的元字符添加到字典键会导致KeyError:

import re

text = "local foals drink cola"

subs_dict = {"(?<=o)a":"w", "l(?=a)":"co"}
subs_regex = re.compile("|".join(subs_dict.keys()))
text = re.sub(subs_regex, lambda match: subs_dict[match.group(0)], text)

>>> KeyError: "a"

如果没有要使用的表达式与空字符串匹配(如果要替换,这是一个有效的假设),则可以在
|
初始化表达式之前使用组,然后检查找到匹配项的组:

(exp1)|(exp2)|(exp3)

或者命名组,这样就不必计算子表达式中的子组

替换功能可以查看哪个组匹配,并从列表中选择替换

我提出了这个实现:


进口稀土
def dictsub(替换,字符串):
“”“事物的形式为{“regex1”:“replacement”,“regex2”:“replacement2”,…}”“”
exprall=re.compile(“|”。.join(“+x+”)表示替换中的x)
gi=1
用_gi={}替换_
对于替换项中的(expr,replacement):
替换\u by \u gi[gi]=替换
gi+=重新编译(expr).groups+1
def选择(匹配):
按[match.lastindex]返回替换项
返回re.sub(exprall、choose、string)
text=“本地小马驹喝可乐”

print(dictsub)({”(?您可以通过将密钥保持为预期匹配,并将replace和regex存储在嵌套的
dict
中来实现这一点。如果您希望匹配特定的字符,则此定义应该有效

subs_dict = {"a": {'replace': 'w', 'regex': '(?<=o)a'}, 'l': {'replace': 'co', 'regex': 'l(?=a)'}}
subs_regex = re.compile("|".join([subs_dict[k]['regex'] for k in subs_dict.keys()]))
re.sub(subs_regex, lambda match: subs_dict[match.group(0)]['replace'], text)

'local fowls drink cocoa'

subs_dict={a:{'replace':'w','regex':'(?通过这种方法,我将如何处理具有多个regex条件的替换?例如,如果我希望“a”在前面加“o”时替换为“w”,而在前面加“c”时替换为“x”?@barnabyclung另一个答案(现已编辑)说明了这一点。你已经测试过了,上面的例子在使用Jonny提供的答案时有效。
import re

text = "local foals drink cola"

subs_dict = {"(?<=o)a":"w", "l(?=a)":"co"}
subs_regex = re.compile("|".join("("+key+")" for key in subs_dict))

group_index = 1
indexed_subs = {}
for target, sub in subs_dict.items():
    indexed_subs[group_index] = sub
    group_index += re.compile(target).groups + 1

text = re.sub(subs_regex, lambda match: indexed_subs[match.lastindex], text)

print(text) # "local fowls drink cocoa"
subs_dict = {"a": {'replace': 'w', 'regex': '(?<=o)a'}, 'l': {'replace': 'co', 'regex': 'l(?=a)'}}
subs_regex = re.compile("|".join([subs_dict[k]['regex'] for k in subs_dict.keys()]))
re.sub(subs_regex, lambda match: subs_dict[match.group(0)]['replace'], text)

'local fowls drink cocoa'