[Tutor] Can re do this?

R. Alan Monroe amonroe at columbus.rr.com
Tue Aug 31 00:22:16 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?

Exactly. Only when surrounded by certain words. For some reason I felt
like I was "cheating" or "doing it wrong" by replacing "the lazy dog"
with "the xxx dog", rather than paring down to just the single word
that was changing. But it was just a one off program so I went ahead
and did it that way :^)

The actual file was going from
blah blah, password: "somepass", blah blah
blah blah, password: "xxxxxx", blah blah
Where the length of the password could vary.

I ended up doing something like (from memory, it was at work)
re.compile('password: \".+\",') and just replacing it with the literal
string 'password: "xxxxxx",'.


More information about the Tutor mailing list