Home > Software design >  Multiple replacement for same pattern with regex
Multiple replacement for same pattern with regex

Time:01-04

this piece of code does the replacement in a string using regex and python. With count flag you can also say how many instances to replace.

first = "33,33"
second = '22,55'
re.sub(r"\d \,\d ", first, "There are 2,30 foo and 4,56 faa", count=1)
output: 'There are 33,33 foo and 4,56 faa'

But, how do I do multiple (different value) replace for the same pattern? I want something like:

re.sub(r"\d \,\d ", [first,second], "There are 2,30 foo and 4,56 faa", count=2)
desired output: 'There are 33,33 foo and 22,55 faa'

CodePudding user response:

We can use re.sub with a callback function:

inp = "There are 2,30 foo and 4,56 faa"
repl = ["33,33", "22,55"]
output = re.sub(r'\d ,\d ', lambda m: repl.pop(0), inp)
print(output)  # There are 33,33 foo and 22,55 faa

CodePudding user response:

You can use iter to do the task:

import re

first = "33,33"
second = "22,55"

i = iter([first, second])

out = re.sub(r"\d \,\d ", lambda _: next(i), "There are 2,30 foo and 4,56 faa")
print(out)

Prints:

There are 33,33 foo and 22,55 faa
  • Related