tags:

views:

49

answers:

2

Here's the code I'm running:

import re

FIND_TERM = r'C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec\.exe'
rfind_term = re.compile(FIND_TERM,re.I)

REPLACE_TERM = 'C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\DTExec.exe'

test = r'something C:\Program Files\Microsoft SQL Server\90\DTS\Binn\DTExec.exe something'

print rfind_term.sub(REPLACE_TERM,test)

And the result I get is:

something C:\Program Files\Microsoft SQL Server@\DTS\Binn\DTExec.exe something

Why is there an @ sign?

+2  A: 

You're mixing raw ( r'' ) and normal strings.

>>> FIND_TERM = r'C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec\.exe'
>>> REPLACE_TERM = r'C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\DTExec.exe' 
>>> rfind_term = re.compile(FIND_TERM,re.I)
>>> test = r'something C:\Program Files\Microsoft SQL Server\90\DTS\Binn\DTExec.exe something'
>>> print rfind_term.sub(REPLACE_TERM,test) 
something C:\Program Files\Microsoft SQL Server\100\DTS\Binn\DTExec.exe something
pycruft
why do you need r' and double backslahes in the replace term? Is it because it thinks replace term is a regular expression?
Greg
yes, exactly that : http://docs.python.org/library/re.html
pycruft
+1  A: 

The RE engine is treating the \100 in REPLACE_TERM as an octal escape code. You need to escape the backslash so that it's treated as desired.

Ignacio Vazquez-Abrams
But I'm already escaping the backslash. Why would I need to escape it twice?
Greg
You're escaping the backslash for Python. You still need to escape it for the `re` engine, so that it isn't considered a backreference or octal escape sequence.
Ignacio Vazquez-Abrams