[Tutor] Example of use of (?P<name>) and (?P=name) in Python regular expressions?
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:
> and then refer to them using:
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
x = 'Free Fri Fro Fro From'
y = re.sub(
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.
More information about the Tutor