Regular Expression for pattern substitution

George Sakkis gsakkis at rutgers.edu
Fri Jul 1 19:09:23 CEST 2005


"Deval L" wrote:

> re.replace.

There isn't a re.replace; be careful when you reply to newbies.

> "Vibha Tripathi" wrote:
>
> > It'd be silly to write the code for it if it already
> > exists somewhere in the Python re or sre library
> > module:
> >
> > I need to find and replace all strings in a text file
> > from a certain pattern to another pattern.
> >
> > so for example if I see 'this(\D*)that' anywhere in
> > the file then I'd like to make is 'that(\D*)this'
> > where the middle part of the strings remains
> > unmodified.
> >
> > Any suggestions?
> >
> > Peace.
> > Vibha

Fire up the interpreter and write:

>>> import re
>>> line = 'see this man with that woman holding this dog and that cat'
>>> r = re.compile(r'this(\D*?)that')
>>> r.sub(r'that\1this',line)
'see that man with this woman holding that dog and this cat'


George




More information about the Python-list mailing list