4

我正在尝试替换字符串中特定数字的所有出现。例如,假设我想用另一个替换给定数字的特定实例:

>>> number1 = 33
>>> number2 = 1
>>> re.sub('(foo)%i' % number1, '\\1%i' % number2, 'foo33')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/home/david_clymer/Development/VistaShare/ot_git/lib/python2.4/sre.py", line 142, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "/home/david_clymer/Development/VistaShare/ot_git/lib/python2.4/sre.py", line 260, in filter
    return sre_parse.expand_template(template, match)
  File "/home/david_clymer/Development/VistaShare/ot_git/lib/python2.4/sre_parse.py", line 784, in expand_template
    raise error, "invalid group reference"
sre_constants.error: invalid group reference
>>> re.sub('(foo)%i' % number1, '\\1 %i' % number2, 'foo33')
'foo 1'

如何防止组参考与以下数字混为一谈?

4

2 回答 2

4
import re

number1 = 33
number2 = 1
print re.sub('(foo)%i' % number1, '\g<1>%i' % number2, 'foo33')

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

除了如上所述的字符转义和反向引用之外,\g<name>将使用由名为 name 的组匹配的子字符串,如(?P<name>...)语法所定义。\g<number>使用对应的组号;\g<2>因此等价于\2,但在诸如\g<2>0. \20将被解释为对第 20 组的引用,而不是对后跟文字字符“0”的第 2 组的引用。反向引用\g<0> 替换了 RE 匹配的整个子字符串。

http://docs.python.org/2/library/re.html#module-re

于 2013-03-01T23:08:48.223 回答
1

可以使用以下方法引用显然命名的组\g<name>

>>> re.sub('(?P<prefix>foo)%i' % number1, '\\g<prefix>%i' % number2, 'foo33')
'foo1'

python 文档re.sub()实际上解释了这一点。去图:http ://docs.python.org/2/library/re.html

于 2013-03-01T23:04:09.503 回答