re.sub: escaping capture group followed by numeric(s)

Jon Clements joncle at googlemail.com
Fri Sep 17 21:00:58 CEST 2010


On 17 Sep, 19:59, Peter Otten <__pete... at web.de> wrote:
> Jon Clements wrote:
> > (I reckon this is probably a question for MRAB and is not really
> > Python specific, but anyhow...)
>
> > Absolutely basic example: re.sub(r'(\d+)', r'\1', 'string1')
>
> > I've been searching around and I'm sure it'll be obvious when it's
> > pointed out, but how do I use the above to replace 1 with 11?
> > Obviously I can't use r'\11' because there is no group 11. I know I
> > can use a function to do it, but it seems to me there must be a way
> > without. Can I escape r'\11' somehow so that it's group 1 with a '1'
> > after it (not group 11).
>
> Quoting
>
> http://docs.python.org/library/re.html#re.sub
>
> """
> 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.
> """
>
> Peter

Thanks Peter and MRAB. I must have been through the docs half a dozen
times and missed that - what a muppet! One of those days I guess...

Cheers,

Jon.



More information about the Python-list mailing list