Return to Snippet

Revision: 7426
at July 23, 2008 14:51 by vasilije


Initial Code
import re


def replace(match, withwhat):
    
    starttext = match.group(0)
    n = len(withwhat)
    off = match.start(0)
    
    tmp = starttext
    for i in range(n):
            delta = len(tmp)-len(starttext)
            tmp = tmp[:match.start(i+1)-off+delta ] + withwhat[i](match.group(i+1)) + tmp[match.end(i+1)-off+delta:]
    return tmp
    
#test
funcs = [lambda x: '1'+x+'1',lambda x: '2'+x+'2']
#regex contains 2 capturing groups
print re.sub(regex, lambda x: replace(x, funcs), text)

Initial URL


Initial Description


Initial Title
python search-replace on a match with n non-nested groups

Initial Tags
regex, textmate, python

Initial Language
Other