I am trying to replace the Nth appearance of a needle in a haystack. I want to do this simply via re.sub(), but cannot seem to come up with an appropriate regex to solve this. I am trying to adapt: http://docstore.mik.ua/orelly/perl/cookbook/ch06_06.htm but am failing at spanning multilines, I suppose.
My current method is an iterative approach that finds the position of each occurrence from the beginning after each mutation. This is pretty inefficient and I would like to get some input. Thanks!
I’ve been struggling for a while with this, but I found a solution that I think is pretty pythonic:
EDIT: the matcher consists of two parts:
the
alternate(n)function. This returns a generator that returns an infinite sequence True/False, where every nth value is True. Think of it likelist(alternate(3)) == [False, False, True, False, False, True, False, ...].The
match(m)function. This is the function that gets passed tore.sub: it gets the next value inalternate(n)(gen.next()) and if it’sTrueit replaces the matched value; otherwise, it keeps it unchanged (replaces it with itself).I hope this is clear enough. If my explanation is hazy, please say so and I’ll improve it.