1

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 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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...'

1 Comment

Thanks. That's exactly what I was thinking of.
2

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')

1 Comment

I updated my example to show why this wouldn't work. I'm curious how to do it with re.sub regardless.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.