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" ?
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 group20
, not a reference to group2
followed by the literal character'0'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With