python搜索替换n个非嵌套组的匹配

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python搜索替换n个非嵌套组的匹配相关的知识,希望对你有一定的参考价值。

  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)

以上是关于python搜索替换n个非嵌套组的匹配的主要内容,如果未能解决你的问题,请参考以下文章