[Tutor] Example of use of (?P<name>) and (?P=name) in Python regular expressions?

Kent Johnson kent37 at tds.net
Sun Nov 29 02:58:54 CET 2009


On Sat, Nov 28, 2009 at 6:15 PM, Michael Hannon <jm_hannon at yahoo.com> wrote:
> Greetings.  While looking into the use of regular expressions in Python, I saw that it's possible to name match groups using:
>
>    (?P<name>...)
>
> and then refer to them using:
>
>    (?P=name)
>
> I was able to get this to work in the following, nonsensical, example:
>
>    >>> x = 'Free Fri Fro From'
>    >>> y = re.sub(r'(?P<test>\bFro\b)', r'Frodo (--matched from \g<test>)', x)
>    >>> y
>    'Free Fri Frodo (--matched from Fro) From'
>    >>>
>
> But, as you can see, to refer to the match I used the "\g" notation (that I found some place on the web).

?P= is a matching pattern that you use within the regex to match a
previously seen (and named) pattern. \g is a substitution pattern used
in the replacement text. For (a not very interesting) example, to
replace from 'Fro' to the last 'Fro':

In [2]: x = 'Free Fri Fro From'

In [3]: re.sub(r'(?P<test>Fro).*(?P=test)', 'xx', x)
Out[3]: 'Free Fri xxm'

For aslightly more interesting example, here (?P<test>Fr\w\w) matches
the first 'Free' so (?P=test) matches the second 'Free':
In [6]: x = 'Free Fri Free From'

In [7]: re.sub(r'(?P<test>Fr\w\w).*(?P=test)', 'xx', x)
Out[7]: 'xx From'

Kent


More information about the Tutor mailing list