efficient mega-replacements

Darrell dgallion1 at yahoo.com
Wed Jan 23 21:51:04 EST 2002


String replace is clearly fast.

But when using re, I use the idea of a result list.
A find produces a list like this [(start, seqNum, end), ....]
Replacement text can be associated with the results of a find
[(start, seqNum, end, newText), .....]
Then multiple lists are combined, sorted and the final buffer is written.
This is worth the effort when you have many search and replace re's and the 
buffer is very large. This list is handy when doing complex things.

You might also try something like this.
====Untested code====

def callBack(mo):
        groups = mo.groups()
        for x in range(len(groups)):
                if groups[x] != None:
                        # Not reentrant but fun, using callBack as an object.
                        return callBack.newStrings[x]
        
newStrings=['a','b','c']
callBack.newStrings=newStrings
re.sub("(pat1)|(pat2)|(pat3)", callBack, buf)

--Darrell 



Clark C . Evans wrote:
> Is there an efficient way to do multiple replacements?
> 
>             val = val.replace("'","''")\
>                      .replace("\\","\\\\\\\\\\\\\\\\")\
>                      .replace(chr(13)+chr(10),"\\\\\\\\n")\
>                      .replace(chr(10),"\\\\\\\\n")\
>                      .replace(chr(13),"\\\\\\\\n")\
>                      .replace('"','\\\\"')
> 
> Or is this the best way to do it?
> 
> Best,
> 
> Clark




More information about the Python-list mailing list