python - 在 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 代码不得对查询进行任何更改)
解决方案
推荐阅读
- r - 计算总分并根据输入进行分类
- javascript - request.auth != null 和 request.auth == null 不授予访问权限,其中 true 确实如此-firebase stoarge
- scala - Mill 全局配置编译错误
- loops - 用于 openByUrl 的 Google 表格脚本,带有来自列表的 URL(URL 循环)
- python - 由于“形状不匹配”,Interactive Imputer 不能接受 PLSRegression() 作为估计器
- python - 多次编辑多行字符串中的值并创建大量新字符串?
- javascript - 在 API 请求之前读取变量值(更改其值)
- c++ - C++ 使用 google Protobuf2 和 protobuf3 依赖项?
- android - 带有来自 tflite Model-maker 的模型的错误 Android 对象检测应用程序
- python - 如何获得基于熊猫中其他列的列的较小值?