正则表达式替换中的 Python 转义字符串

标签 python regex escaping

下面代码的输出:

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/

相关文章:

python - 获取 python 字典的值

python - Python 中的内存感知 LRU 缓存?

java - 在java字符串文字中转义反斜杠

c++ - 如何使用反斜杠对字符串进行字符串化

mysql:如何转义perl字符串中的括号

python - Django 1.7 : Makemigration: non-nullable field

php - 为什么从 Web 服务器执行时 Python 环境变量不同?

regex - Bash 脚本 - 用于转储文件列表的正则表达式

java - 优化段落中查找单词

javascript - 从背景颜色中分离出 alpha 值,从字符串转换为数字,然后验证