re module substitution confusion

D

Doug Farrell

Hi all,

I'm trying to do the following from within a code module:

import re

# text to match
text = "Good morning x something /x, how are you today x something
else /x"

# pattern to match
regex = re.compile("(x)(.*?)(/x)", re.DOTALL)

# find first match
m = re.search(regex, text)

# keep looking while there are matches
while m != None:
# substitute in some other text for the exact match
text = re.sub(m.group(), "Mr. Phelps", text)

# find the next match
m = re.search(regex, text)

print text

This works within the Python shell, but I can't seem to make it work
from within a program. It would seem like the re.sub(m.group()...)
would work fine as m.group() just returns the matched string
completely.

Any help would be greatly appreciated,
Doug Farrell
 
D

Doug Farrell

Hi all,

I got a direct email from someone (who I can't remember right now) who
suggested that I wasn't very clear about what I was trying to do and
what was wrong. In an attempt to clarify I'm adding this post. :)

I'm trying to create a little Python CGI program that will read in a
HTML template file that has Python code embedded in it between
<python> ... </python> tags. So I'd like to use the re module to find
the following pattern:

pattern = re.compile("(<python>)(.*?)(</python>)", re.DOTALL)

Doing a search with this pattern like this:

match = re.search(pattern, text)

where text equals the HTML template file in string form, will find all
the code segments. I then pull out the code segment and pass it to
exec() to execute it. I can capture the output of the exec() call by
redirecting sys.stdout to a StringIO object. The problem is that this;
I can match the <python>...</python> segments no problem. But I only
want to replace each one in turn with the results of the exec() call.
If I do this:

text = re.sub(pattern, ".. exec() output..", text) it replaces all the
code segments, not just the one that was matched. I need to substitute
in the output of the exec() (which is a string when I'm done) into the
one place it came from.

Hope this clears up any confusion.

I didn't include the whole program in my first post as it's kind of
long. I thought the sections I included above were enough information
to follow what I'm trying to do, at least I hope so.

Thanks again in advance for your help,
Doug
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top