In the following content, I want to replace what is inside --START-- / --END-- by a string filelist containing both:
\character- newlines (
\n)
This code nearly works:
import re
content = """A
--START--
tobereplaced
--END--
C"""
filelist = """c:\\test\\l1.txt
c:\\test\\l2.txt"""
print(re.sub(r'(--START--\n).*?(\n--END--)', r'\1' + re.escape(filelist) + r'\2',
content, flags=re.MULTILINE | re.DOTALL))
but:
without
re.escape(...), it fails because of the\\l. One solution might be to hack every\as'\\\\'orr'\\', but it's not really elegant (in my real code,filelistis read from a file produced by another tool)with
re.escape(...), then in the output, every newline has a trailing\and every.becomes\.which I don't want:A --START-- c:\test\l1\.txt\ c:\test\l2\.txt --END-- C
How to fix this? and how re.sub(..., r'\1' + repl + r'\2', ...) treat repl as a normal string and no regex pattern?
Desired output:
A
--START--
c:\test\l1.txt
c:\test\l2.txt
--END--
C