[Tutor] Can re do this?

Rich Krauter rmkrauter at yahoo.com
Mon Aug 30 18:45:47 CEST 2004


R. Alan Monroe wrote:
> Given a test file like:
> The quick brown fox jumps over the lazy log
> Another test line lazy dog
> 
> I want to match lines containing "the lazy dog" (line 2 would not
> match). This I can do. I then want to change "lazy" to "xxx" (in line
> 1 but not line 2). This is where I'm getting stuck. I can't figure out
> how to replace just a subset of "the lazy dog", which is itself, a
> subset of the entire line.
> 

Depending on your requirements, maybe re is overkill.

 >>> mystr = 'The quick brown fox jumps over the lazy dog'
 >>> target = 'the %s dog'
 >>> tmp =  mystr.replace(target%'lazy',target%'happy')
 >>> tmp
'The quick brown fox jumps over the happy dog'


The real question is whether 'the' and 'dog' have to be patterns too? 
i.e. do you want to replace 'lazy' only when it's surrounded by certain 
patterns, as opposed to being surrounded by pre-determined strings, as 
done above?

Good luck.

Rich


More information about the Tutor mailing list