python无效组引用\ 10\2

Eri*_* H. 6 python regex

如果我想在第一个组引用后插入"0",那么语法是什么?

import re
re.sub("(..)(..)", "\\1x\\2", "toto")
toxto
re.sub("(..)(..)", "\\10\\2", "toto")
sre_constants.error: invalid group reference
Run Code Online (Sandbox Code Playgroud)

错误,因为\ 10被解释为第10个参考组(这就是为什么在ed()中,组引用在[1-9]间隔中).

在上面的例子中,如何获得"to0to"?

Ash*_*ary 9

您可以使用\g基于组的替换:

>>> import re
>>> re.sub("(..)(..)", r"\g<1>0\g<2>", "toto")
'to0to'
Run Code Online (Sandbox Code Playgroud)

来自docs:

\g<number>使用相应的组号; \g<2>因此,等同于\2,但在替代品中并不含糊\g<2>0. \20将被解释为对组的引用20,而不是对组2后跟文字字符的引用'0'.

  • 您可能想引用[文档](http://docs.python.org/2/library/re.html#re.sub):*`\ g <number>`使用相应的组号; 因此`\ g <2>`相当于`\ 2`,但在诸如`\ g <2> 0`之类的替换中并不含糊.* (2认同)