replacing all 'rng's in a buffer with consecutive r[1], r[2]'s

Peter Otten __peter__ at web.de
Wed Oct 4 08:41:15 EDT 2006


m g william wrote:

> I read a file into a buffer and subject it to re.sub()
> I can replace every occurrence of a pattern with a fixed string but when
> I try to replace each occurrence with a string that changes (by having
> an incrementing number in it, (ie 'repTxt[1]','repTxt[2]'etc), I note
> that the incrementing number generator function, I'm calling in
> re.sub(), (which works fine outside it), seems to be evaluated only once
> and is therefore not incrementing the number.
> 
> Can someone please show me a working eg of how to replace 'rng' in a
> file with 'r[1]', 'r[2]' etc. This is my first Python program so any
> help would be very gratefully received.
> 
> buf = pat.subn('rng[' + static() + ']', buf, 0)

You'll have to repeat that to get the desired effect:

pat = re.compile("rng")
replacements = 1
while replacements:
    buf, replacements = pat.subn("r[" + static() + "]", buf, 1)
    print buf

but there is a more efficient alternative

def fsub(match):
    return "r[" + static() + "]"
buf = re.sub("rng", fsub, buf)

that would still work if you were to replace 'rng' with 'rng[1]',
'rng[2]'...

Peter



More information about the Python-list mailing list