How to distinguish a group link from the number that follows it?

I am trying to replace all incidents of a certain number inside a string. For example, let's say I want to replace individual instances of a given number with another:

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

How can I save a link to a group with the following number?

+4
source share
2 answers
 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 screens and backreferences, as described above, \g<name> will use a substring corresponding to a group named name, as defined by the syntax (?P<name>...) . \g<number> uses the number of the corresponding group; \g<2> therefore equivalent to \2 , but is not ambiguous in replacement, for example, \g<2>0 . \20 will be interpreted as a reference to group 20, not a link to group 2 followed by the literal character "0". The backlink \g<0> replaces the entire substring corresponding to RE.

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

+4
source

Apparently, the named groups can be referenced using \g<name> :

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

The python re.sub() for re.sub() really explain this. Go digital: http://docs.python.org/2/library/re.html

+1
source

All Articles