用长度相同的字符串替换正则表达式

2024-10-01 09:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用一系列重复的字符替换XML标记,这些字符与标记的字符数相同。在

例如:

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

我想换成:

^{pr2}$

我们如何使用正则表达式来实现这一点?在


Tags: 标记xml字符pr2lastsaved
1条回答
网友
1楼 · 发布于 2024-10-01 09:21:39

^{}接受函数作为替换:

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.

下面是一个例子:

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##############'

我使用的模式可能需要一些润色,我不确定匹配XML标记的标准解决方案是什么。但你明白了。在

相关问题 更多 >