re module substitution confusion
Piet van Oostrum
piet at cs.uu.nl
Tue Jul 8 06:56:24 EDT 2003
>>>>> writeson at earthlink.net (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 = re.search(regex, 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(m.group(), "Mr. Phelps", text)
DF> # find the next match
DF> m = re.search(regex, 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(m.group()...)
DF> would work fine as m.group() 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 cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl
More information about the Python-list
mailing list