embedding executable code in a regular expression in Python

Ben C spamspam at spam.eggs
Sun Jul 16 17:43:49 EDT 2006


On 2006-07-16, Avi Kak <kak at purdue.edu> wrote:
> 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?

You can use sub and make the replacement pattern a function (or any
"callable" thing) and it gets called back with the match object:

    import re

    def f(mo):
        if "hello" in mo.groups():
            print "saw hello"
        if "mello" in mo.groups():
            print "saw mello"

    re.sub(r'(hello)(mello)', f, "jellohellomello")

Actually I didn't know you could do that in Perl. The time I've found
this useful in Python is substitutions to convert e.g.
"background-color" into "backgroundColor"; a function turns the c into
C. I always assumed in Perl you would need to use eval for this, but
perhaps there is another way.



More information about the Python-list mailing list