Replacing a RegEx with a string of characters with the same length

前端 未结 1 1843
自闭症患者
自闭症患者 2020-12-10 15:27

I want to replace XML tags, with a sequence of repeated characters that has the same number of characters of the tag.

For example:



        
相关标签:
1条回答
  • 2020-12-10 15:33

    re.sub accepts a function as replacement:

    re.sub(pattern, repl, string, count=0, flags=0)
    

    If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

    Here's an example:

    In [1]: import re
    
    In [2]: def repl(m):
       ...:     return '#' * len(m.group())
       ...: 
    
    In [3]: re.sub(r'<[^<>]*?>', repl,
       ...:     '<o:LastSaved>2013-01-21T21:15:00Z</o:LastSaved>')
    Out[3]: '#############2013-01-21T21:15:00Z##############'
    

    The pattern I used may need some polishing, I'm not sure what's the canonical solution to matching XML tags is. But you get the idea.

    0 讨论(0)
提交回复
热议问题