FW: [Tutor] Your good advice about Regular Expressions
Seabrook, Richard
rhseabrook@aacc.edu
Sat Jun 21 21:59:02 2003
I apologize to the poster and to the list -- I wrote to=20
the poster directly instead of to the list and this is=20
his reply.
Dick S.
-----Original Message-----
From: Karl Pfl=E4sterer [mailto:sigurd@12move.de]
Sent: Sat 6/21/2003 8:05 PM
To: Seabrook, Richard
Cc:=09
Subject: Re: [Tutor] Your good advice about Regular Expressions
On 21 Jun 2003, Seabrook, Richard <- rhseabrook@aacc.edu wrote:
Please write next time your email to the list address so everyone can
read it. As I don't know why you didn't it for now I send it only back
to you.
> I'm most familiar with using \( ...\) to tag a=20
> pattern for later recall as \1, \2, etc., however many
> items have been tagged. Is this not possible in Python
> regular expressions?
Yes backreferences are possible in Python. To tag groups you enclose
them in simple parenthesis not in escaped parentheses. Escaped
parenthesis (like yours =BB\(=AB) simply mean a parentheses in the =
search
text.
But Python has something more convenient for backreferences if you have
deep nesting and want to avoid to reference the wrong group: named
groups.
To define a group you write `(P<text>..)' and for a backreference you
write (P=3Dtext..). But you can also use \number for a backreference.
Eg.
$ python
Python 2.2.2 (#1, Feb 3 2003, 14:10:37)=20
[GCC 3.2 20020927 (prerelease)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sre
>>> reg =3D sre.compile(r'(?P<word>\b\w+\b).+(?P=3Dword)')
>>> pat =3D reg.match("Dies ist ein Test Dies")
>>> pat.group()
'Dies ist ein Test Dies'
>>> pat.group(1)
'Dies'
>>> pat.group('word')
'Dies'
>>> reg =3D sre.compile(r'(?P<word>\b\w+\b).+\1')
>>> pat =3D reg.match("Dies ist ein Test Dies")
>>> pat.group()
'Dies ist ein Test Dies'
>>>=20
The Python library reference writes a bit about that but a IMO better
explaination can be found at http://www.python.org/doc/howto . There is
a regexp howto which explains all these items excellent.
HTH
bye
Karl
--=20
Increasingly, people seem to misinterpret complexity as
sophistication, which is baffling -- the incomprehensible should cause
suspicion rather than admiration. Possibly this trend results from a
mistaken belief that using a somewhat mysterious device confers an
aura of power on the user. -- Niklaus =
Wirth