Regular Expressions to Replace Strings
Trent Mick
trentm at ActiveState.com
Wed May 16 11:39:37 EDT 2001
On Wed, May 16, 2001 at 01:58:39PM +0000, Colin Meeks wrote:
> I'm trying to open a text file and do a search and replace that is case
> insensitive and replaces all occurances. I have the following code, but it
> has problems if the word exists in the string. Does anybody have any ideas
> what I'm doing wrong.
>
> PageRoot="../pages/contactus.ptm"
> UseRoot=open(PageRoot, "r").read()
> UseWord="python"
You want parentheses around the search pattern so it get put in a "group".
So,
>>> text = "ads flakjefae Pythonafeaef apythonasfae"
>>> import re
>>> pat = re.compile("(python)", re.I)
>>> pat.sub('<B>\\1</B>', text)
'ads flakjefae <B>Python</B>afeaef a<B>python</B>asfae'
>>>
> pat=re.compile(UseWord,re.I)
> UseRoot=pat.sub('<B>\\1</B>', UseRoot)
>
> The error I get is unknown group number. Thanks in advance. I want to use
> this code as part of my search engine, so the word will always be a
> variable.
>
Cheers,
Trent
--
Trent Mick
TrentM at ActiveState.com
More information about the Python-list
mailing list