python - 使用 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)'
解决方案
您可以将替换列表转换为迭代器并使用该next
函数来避免需要全局计数器:
replacementIter = iter(replacements)
def repl(m):
return next(replacementIter)
new = re.sub(r'\[(.*?)]', repl, original_expression)
推荐阅读
- javascript - React TypeError:无法读取未定义的属性“包含”
- python - 如何在遍历 webelements 时摆脱 None ?
- ionic-framework - 如何导航到 ionic 5 应用程序的外部 Web url
- css - 如何在 Flexdashboard 中将我的标签集更改为药丸?
- r - paste0() changes format of date
- batch-file - 文件夹内的批处理文件以创建 MediaInfo.nfo 文件
- laravel - 合并为一个集合
- javascript - 在javascript中将字符串解析为二维整数数组
- node.js - 在 vscode 中使用 Typescript 时,我无法让智能感知工作
- amazon-web-services - 我们应该在 Redshift 的存储过程中使用 udf