tags:

views:

69

answers:

4

Say I have text 'C:\somedir\test.log' and I want to replace 'somedir' with 'somedir\logs'.

So I want to go from 'C:\somedir\test.log' to 'C:\somedir\logs\test.log'

How do I do this using the re library and re.sub?

I've tried this so far:

find = r'(C:\\somedir)\\.*?\.log'
repl = r'C:\\somedir\\logs'
print re.sub(find,repl,r'random text ... C:\somedir\test.log more \nrandom \ntext C:\somedir\test.xls...')

But I just get 'C:\somedir\logs'

+4  A: 

You should be using the os.path library to do this. Specifically, os.path.join and os.path.split.

This way it will work on all operating systems and will account for edge cases.

ikanobori
You're right, but for curiosity's sake, how would I do this with re.sub?
Greg
+2  A: 

ikanobori is correct, but you should also not be using re for simple string substitution.

r'C:\somedir\test.log'.replace('somedir', r'somedir\logs')
Nathon
I updated my example to show why this wouldn't work. I'm curious how to do it with re.sub regardless.
Greg
+2  A: 

You need to introduce a different grouping in order for the replace to work as you want, and then need to refer to that group with the replacement expression. See Python's re.sub documentation for another example.

Try:

find = r'C:\\somedir\\(.*?\.log)'
repl = r'C:\\somedir\\logs\\\1'
print re.sub(find,repl,r'random text ... C:\somedir\test.log more \nrandom \ntext C:\somedir\test.xls...')

This results in output:

'random text ... C:\somedir\logs\test.log more \nrandom \ntext C:\somedir\test.xls...'
Nathan Ernst
Thanks. That's exactly what I was thinking of.
Greg
+1  A: 

Alright, if you really want a way to do it with regular expressions, here's one:

find = r'(C:\\somedir\\.*?\.log)'
def repl(match):
    return match.groups()[0].replace('somedir', r'somedir\logs')
s = r'random text ... C:\somedir\test.log more \nrandom \ntext C:\somedir\test.xls...'
print re.sub(find, repl, s)
Nathon