Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

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

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

For example:

<o:LastSaved>2013-01-21T21:15:00Z</o:LastSaved>

I want to replace it with:

#############2013-01-21T21:15:00Z##############

How can we use RegEx for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...