如何使用正则表达式和列表替换特定位置?

How to substitute specific positions using regex and lists?

假设我在 Python 中有以下字符串:

s = "Hi, I currently have 2 apples and 3 oranges"

在正则表达式中我们可以做到

r = re.findall(r'\d',s) 

这会给我们一个包含数字的列表: ["2","3"]

但是,假设我想按照它们在句子中出现的顺序使用列表替换这些数字。

new_list = ["4","5"]

并让新句子说:

"Hi, I currently have 4 apples and 5 oranges"

我尝试执行以下操作:

new_sentence = [re.sub(('\d'),x, s) for x in new_list]

但这给了我:

['Hi, I currently have 4 apples and 4 oranges', 'Hi, I currently have 5 apples and 5 oranges']

这不是我想要的。如何使用正则表达式按照列表中出现的顺序替换值?

您可以从 new_list 创建一个迭代器并在 re.sub 中使用它:

import re


s = "Hi, I currently have 2 apples and 3 oranges"
new_list = ["4", "5"]

new_list_iter = iter(new_list)

out = re.sub(r"\d+", lambda _: next(new_list_iter), s)
print(out)

打印:

Hi, I currently have 4 apples and 5 oranges

这是另一个解决方案

''.join(map( operator.add, 
             re.split('\d+', s), 
             ['4','5']+[''] 
))

当 map 接收到多个这样的可迭代对象时,它首先将两个可迭代对象中的第一个项目作为参数发送到 operator.add 函数,然后是下两个项目,依此类推。我们必须在替换值的末尾添加一个空字符串,使其与 re.split.

的长度相同