[Tutor] Example of use of (?P<name>) and (?P=name) in Python regular expressions?
Martin Walsh
mwalsh at mwalsh.org
Sun Nov 29 02:26:15 CET 2009
Michael Hannon 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'm not sure you've got that quite right. IIUC, the (?P=name) syntax is
used to match a previously defined group, "in the regular expression
itself." (http://docs.python.org/library/re.html)
<snip>
x = 'Free Fri Fro Fro From'
y = re.sub(
r'(?P<test>Fro) (?P=test)',
r'Frodo (--matched from \g<test>, twice in a row)', x
)
# y == 'Free Fri Frodo (--matched from Fro, twice in a row) From'
> But, as you can see, to refer to the match I used the "\g" notation (that I found some place on the web).
The \g notation is appropriate for re.sub.
HTH,
Marty
More information about the Tutor
mailing list