1

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)

pistachio
  • 11
  • 1
  • You do not need a regex to escape the replacement pattern, you may use `query = query.replace('\\', '\\\\')` (same for template). Do not replace ``\\`` with ``\`` at the end – Wiktor Stribiżew May 19 '20 at 08:10

0 Answers0