Regular Expression for pattern substitution

James Stroud jstroud at mbi.ucla.edu
Sun Jul 3 02:09:45 CEST 2005


You might want to be a little more explicit. Do you know that

this = "this"
that = "that"

or do you mean 

this = `the part before the \D*`
that = `the part after the \D*`

If you mean the former, then the previously proposed

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

will do fine.

If you mean the latter, then you should describe the type of pattern that
this and that belong to. Also, consider how greedy your \D* is:

py> line = 'this abcd this efgh that'
py> r.sub(r'that\1this',line)
'that abcd this efgh this'

Would this be the result you expect?






James

On Friday 01 July 2005 09:39 am, 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
>
> PS. How do I avoid getting my email ID web-published
> for this mailing list.?
>
>
>
> ____________________________________________________
> Yahoo! Sports
> Rekindle the Rivalries. Sign up for Fantasy Football
> http://football.fantasysports.yahoo.com

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list