用列表中的项目按顺序替换字符串中的正则表达式匹配项 [英] Replace regex matches in a string with items from a list in order
问题描述
例如,我有一个像这样的字符串:
'blah blah 1.344 blah 1.455'
和一个列表:
[2.888, 4.033]
我知道字符串和列表包含相等数量的数字,并且想使用正则表达式将字符串中的所有数字替换为列表中的数字.我想要类似的东西:
re.sub('\d\.\d+', list[i], line)
但不知道如何让它用列表中的下一个项目替换每个匹配项,而不仅仅是同一个项目.我想保留所有文本和所有空格完全相同,因此拆分为列表、用索引替换并重新连接似乎不是我需要的.
re.sub
可以是一个任意函数,它接受一个 match
对象并返回一个字符串来替换它.在你的情况下:
For example, I've got a string like:
'blah blah 1.344 blah 1.455'
and a list like:
[2.888, 4.033]
I know that the string and the list contain an equal quantity of numbers and want to replace all the numbers in the string with the numbers from the list using regex. I want something like:
re.sub('\d\.\d+', list[i], line)
but don't know how to make it replace each match with the next item from list, not just the same item. I want to preserve all of the text and all of the whitespace exactly the same, so splitting to a list, replacing by index and joining back seems not to be the thing I need.
The second repl
parameter to re.sub
can be an arbitrary function that takes a single match
object and returns a string to replace it. In your case:
>>> import re
>>> repl = [2.888, 4.033]
>>> re.sub(
r'\d\.\d+', # note raw string to avoid issues with backslashes
lambda match: str(repl.pop(0)), # replace each match with the next item in the list
'blah blah 1.344 blah 1.455'
)
'blah blah 2.888 blah 4.033'
这篇关于用列表中的项目按顺序替换字符串中的正则表达式匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!