我正在尝试替换字符串中所有出现的特定数字。例如,假设我想用另一个替换给定数字的特定实例:
>>> 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'
我怎样才能避免将组引用与以下数字混为一谈?
最佳答案
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)
In addition to character escapes and backreferences as described above,
\g<name>
will use the substring matched by the group named name, as defined by the(?P<name>...)
syntax.\g<number>
uses the corresponding group number;\g<2>
is therefore equivalent to\2
, but isn’t ambiguous in a replacement such as\g<2>0
.\20
would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference\g<0>
substitutes in the entire substring matched by the RE.
关于python - 如何区分组引用和后面的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15168249/