Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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 re.sub进行基于位置的替换_Python_Regex - Fatal编程技术网

使用Python re.sub进行基于位置的替换

使用Python re.sub进行基于位置的替换,python,regex,Python,Regex,给定一个正则表达式模式和一个包含n个模式匹配项的字符串,如何使用n个不同的替换字符串(按顺序)对n个匹配项进行细分 下面是一个玩具的例子,以及我公认的值得畏缩的解决方案 import re # original string provided by the user # in this example the user has chosen a string with n = 3 pattern matches original_expression = '[x] - 2 * [y] + [

给定一个正则表达式模式和一个包含n个模式匹配项的字符串,如何使用n个不同的替换字符串(按顺序)对n个匹配项进行细分

下面是一个玩具的例子,以及我公认的值得畏缩的解决方案

import re

# original string provided by the user
# in this example the user has chosen a string with n = 3 pattern matches 
original_expression = '[x] - 2 * [y] + [z]'

# a separate function will programmatically generate a list of n = 3 replacement strings
replacements = ['(arbitrary replacement 1)', '(arbitrary replacement 2)', '(arbitrary replacement 3)']

# the goal is to replace the three pattern matches with the three replacement strings, by position
counter = -1

def custom_repl(matchobj):
    global counter
    counter += 1
    return replacements[counter]

re.sub(r'\[(.*?)]', custom_repl, original_expression)
此代码生成所需的输出:


'(任意替换1)-2*(任意替换2)+(任意替换3)

您可以将替换列表转换为迭代器,并使用
next
功能避免需要全局计数器:

replacementIter = iter(replacements)

def repl(m):
    return next(replacementIter)

new = re.sub(r'\[(.*?)]', repl, original_expression)

您的代码正在按预期工作,对吗?是的,但我想知道是否有一个规范的解决方案。