简体   繁体   English

Python 用变量替换正则表达式包含特殊字符

[英]Python substitute regex by variable contains special carachter

I'm trying to substitute using re:我正在尝试使用 re 替换:

buffer = 'my_path: any_suffix'
share_path = '\\\\server\\final'
buffer = re.sub('my_path:.*', fr'my_path: {share_path}', buffer)

In the buffer I get:在缓冲区中我得到:

'my_path: \\server\x0cinal'

instead of resired:而不是要求:

'my_path: \\server\final'

If I use share_path = '\\\\server\\Final' (with capital 'F') - it works OK.如果我使用share_path = '\\\\server\\Final' (大写'F') - 它可以正常工作。

What can be done?可以做什么?

You need to double escape the backslash in the replacement pattern and it seems the best way to use the variable in this case is to use str.format here rather than the f-string literal ( fr'my_path: {share_path.replace("\\", "\\\\")}' will throw SyntaxError: f-string expression part cannot include a backslash ):您需要在替换模式对反斜杠进行双重转义,在这种情况下使用变量的最佳方法似乎是在此处使用str.format而不是 f 字符串文字( fr'my_path: {share_path.replace("\\", "\\\\")}'将抛出SyntaxError: f-string expression part cannot include a backslash ):

buffer = re.sub('my_path:.*', r'my_path: {}'.format(share_path.replace("\\", "\\\\")), buffer)

See the Python demo .请参阅Python 演示

Code:代码:

buffer.replace('any_suffix', re.sub(r"\\s+", "s", share_path)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM