I have a template file (.txt) which has only paths to some queries (.sql), then in python I try to substitute the paths with the actual queries. The queries have sometimes special characters like \s. The problem is when I use re.sub I get an error like
Traceback (most recent call last):
File "C:\Program Files (x86)\Python38-32\lib\sre_parse.py", line 1039, in parse_template
this = chr(ESCAPES[this][1])
KeyError: '\\s'
Example
import re
template = """some stuff
variable = '@query|query_name';
some other stuff"""
query = """SELECT trim(regexp_replace('John Kowalski', '\\s+', ' ')) FROM DUAL """
output = re.sub("(')@query\|query_name(')", r'\1' + query + r'\2', template)
print(output)
The above code give error like I mention before. I found one solution but I wonder if there is a better way to do this? My solutuon
import re
template = """some stuff
variable = '@query|query_name';
some other stuff"""
query = """SELECT trim(regexp_replace('John Kowalski', '\\s+', ' ')) FROM DUAL """
template = re.sub(r'\\', r'\\\\', template) # template could also have some \
query = re.sub(r'\\', r'\\\\', query)
output = re.sub("(')@query\|query_name(')", r'\1' + query + r'\2', template)
output = re.sub(r'\\\\', r'\\', output)
print(output)
Is there a better way to do this? (Python code must not do any changes to query)