re module substitution confusion

Piet van Oostrum piet at
Tue Jul 8 12:56:24 CEST 2003

>>>>> writeson at (Doug Farrell) (DF) wrote:

DF> Hi all,
DF> I'm trying to do the following from within a code module:

DF> import re

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

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

DF> # find first match
DF> m =, text)

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

DF>     # find the next match
DF>     m =, text)

DF> print text

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

It works for me (python2.2 and 2.3b2).
BTW, you only need the outer parentheses in your r.e.
And be aware that it will, match any x in your text, even when it occurs
inside a word.
Piet van Oostrum <piet at>
Private email: P.van.Oostrum at

More information about the Python-list mailing list