Home > Mobile >  Python substitute regex by variable contains special carachter
Python substitute regex by variable contains special carachter

Time:09-10

I'm trying to substitute using 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.

What can be done?

CodePudding user response:

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):

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

See the Python demo.

CodePudding user response:

Code:

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