Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python re invalid group reference \10\2 [duplicate]

Tags:

python

regex

What would be the syntax if I want to insert "0" after the first group reference ?

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

Error, because \10 is interpreted as 10th reference group (that's why in ed(), group references are in [1-9] interval).

In the example above, how to obtain "to0to" ?

like image 879
Eric H. Avatar asked Jan 13 '14 12:01

Eric H.


1 Answers

You can use \g based group substitution:

>>> import re
>>> re.sub("(..)(..)", r"\g<1>0\g<2>", "toto")
'to0to'

From docs:

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

like image 186
Ashwini Chaudhary Avatar answered Oct 19 '22 20:10

Ashwini Chaudhary