首页 > 解决方案 > 在 python 中使用正则表达式替换时忽略特殊字符

问题描述

我有一个模板文件(.txt),它只有一些查询(.sql)的路径,然后在 python 中我尝试用实际查询替换路径。查询有时有特殊字符,如 \s。问题是当我使用 re.sub 时出现类似错误

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'

例子

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)

上面的代码给出了我之前提到的错误。我找到了一个解决方案,但我想知道是否有更好的方法来做到这一点?我的解决方案

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)

有一个更好的方法吗?(Python 代码不得对查询进行任何更改)

标签: pythonregexspecial-characterssubstitution

解决方案


推荐阅读