embedding executable code in a regular expression in Python

Anthra Norell anthra.norell at tiscalinet.ch
Sun Jul 16 17:55:34 EDT 2006


----- Original Message -----
From: "Avi Kak" <kak at purdue.edu>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Sunday, July 16, 2006 11:05 PM
Subject: embedding executable code in a regular expression in Python


> Folks,
>
> Does regular expression processing in Python allow for executable
> code to be embedded inside a regular expression?
>
> For example, in Perl the following two statements
>
> $regex = qr/hello(?{print "saw hello\n"})mello(?{print "saw
> mello\n"})/;
> "jellohellomello"  =~  /$regex/;
>
> will produce the output
>
>   saw hello
>   saw mello
>
> Is it possible to do the same in Python with any modules that come
> with the standard distribution, or with any other modules?
>
> Thanks in advance for any help,
>
> Avi Kak (kak at purdue.edu)
>
> --
> http://mail.python.org/mailman/listinfo/python-list

There's a new module out that can do it like this:

import SE
Stream_Editor = SE.SE ('<EAT> "~[hm]ello~=print \'saw =\'\n" ')
for line in Stream_Editor ('yellomellojellohello').split ('\n'):
exec ("%s" % line)

saw mello
saw hello

You'll find SE in the Cheese Shop. It has been commented favorably. I
wouldn't comment it, because I wrote it.

Regards

Frederic





More information about the Python-list mailing list