下面代码的输出:
rpl = 'This is a nicely escaped newline \\n'
my_string = 'I hope this apple is replaced with a nicely escaped string'
reg = re.compile('apple')
reg.sub( rpl, my_string )
..是:
'I hope this This is a nicely escaped newline \n is replaced with a nicely escaped string'
..所以打印时:
I hope this This is a nicely escaped newline
is replaced with a nicely escaped string
所以当 python 替换另一个字符串中的“apple”时,它正在取消转义字符串?现在我刚刚完成
reg.sub( rpl.replace('\\','\\\\'), my_string )
这样安全吗?有没有办法阻止 Python 这样做?
最佳答案
来自 help(re.sub)
[强调我的]:
sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.
解决这个问题的一种方法是传递一个 lambda
:
>>> reg.sub(rpl, my_string )
'I hope this This is a nicely escaped newline \n is replaced with a nicely escaped string'
>>> reg.sub(lambda x: rpl, my_string )
'I hope this This is a nicely escaped newline \\n is replaced with a nicely escaped string'
关于正则表达式替换中的 Python 转义字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12127472/