开发者

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\\Micros开发者_StackOverflow中文版oft 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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜