Posted By

vasilije on 07/23/08


Tagged

regex textmate python


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

gartenstuhl


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


 / Published in: Other
 

  1. import re
  2.  
  3.  
  4. def replace(match, withwhat):
  5.  
  6. starttext = match.group(0)
  7. n = len(withwhat)
  8. off = match.start(0)
  9.  
  10. tmp = starttext
  11. for i in range(n):
  12. delta = len(tmp)-len(starttext)
  13. tmp = tmp[:match.start(i+1)-off+delta ] + withwhat[i](match.group(i+1)) + tmp[match.end(i+1)-off+delta:]
  14. return tmp
  15.  
  16. #test
  17. funcs = [lambda x: '1'+x+'1',lambda x: '2'+x+'2']
  18. #regex contains 2 capturing groups
  19. print re.sub(regex, lambda x: replace(x, funcs), text)

Report this snippet  

You need to login to post a comment.