且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用替换函数时,为什么反向引用在 Python 的 re.sub 中不起作用?

更新时间:2022-11-26 14:29:52

因为有更简单的方法可以实现您的目标,所以您可以使用它们.

As there are simpler ways to achieve your goal, you can use them.

正如您已经看到的,您的替换函数将一个匹配对象作为它的参数.

As you already see, your replacement function gets a match object as it argument.

这个对象有一个方法 group() 可以用来代替:

This object has, among others, a method group() which can be used instead:

def dashrepl(matchobj):
    return matchobj.group(0) + ' '

这将准确给出您的结果.

which will give exactly your result.

但您说得完全正确 - 文档 有点令人困惑这样:

But you are completely right - the docs are a bit confusing in that way:

它们描述了 repl 参数:

repl 可以是字符串或函数;如果是字符串,则处理其中的任何反斜杠转义.

repl can be a string or a function; if it is a string, any backslash escapes in it are processed.

如果 repl 是一个函数,它会在每次不重叠的模式出现时被调用.该函数采用单个匹配对象参数,并返回替换字符串.

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.

可以将其解释为函数返回的替换字符串"也适用于反斜杠转义的处理.

You could interpret this as if "the replacement string" returned by the function would also apply to the processment of backslash escapes.

但是由于这个处理过程只针对是字符串"的情况进行描述,所以比较清晰,但乍一看并不明显.

But as this processment is described only for the case that "it is a string", it becomes clearer, but not obvious at the first glance.