Greg
Greg

Reputation: 47124

Python - Strange Behavior in re.sub

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?

Upvotes: 1

Views: 248

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

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.

Upvotes: 1

pycruft
pycruft

Reputation: 68765

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

Upvotes: 2

Related Questions