首页 > 解决方案 > 使用 Python re.sub 进行基于位置的替换

问题描述

给定一个正则表达式模式和一个包含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)

此代码产生所需的输出:

'(arbitrary replacement 1) - 2 * (arbitrary replacement 2) + (arbitrary replacement 3)'

标签: pythonregex

解决方案


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

replacementIter = iter(replacements)

def repl(m):
    return next(replacementIter)

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

推荐阅读