sql - PostgreSQL 正则表达式用条件替换函数
问题描述
有一个 PostgreSQL 表。该表有一个字段,其中包含存储过程的查询作为字符串。我正在寻找一个正则表达式替换解决方案,我能够删除字符串的一部分,但仅在字符串包含“tmp”的情况下。
示例字符串输入:
...from schema1.table_1...
...from schema1.table_1_tmp...
...from schema1.table_2...
...from schema1.table_2_tmp...
目标:
...from schema1.table_1...
...from table_1_tmp...
...from schema1.table_2...
...from table_2_tmp...
schema1
是静态值,只是表名不同。其中一些包含tmp
子字符串,其中一些不包含。
如果它包含 tmp,我们应该删除该schema1
字符串。
解决方案
你可以使用regexp_replace()
如下:
regexp_replace(mycol, '\sschema1\.(\w+_tmp)\s', ' \1 ')
正则表达式分解:
\s a space
schema1\. litteral string "schema1."
( beginning of a capturing group
\w+ at many alphanumeric characters as possible (including "_")
_tmp litteral string "_tmp"
) end of the capturing group
\s a space
当字符串与正则表达式匹配时,匹配表达式被替换为:一个空格,然后是捕获的部分,然后是另一个空格。
with t as (
select '... from schema1.table_1_tmp ...' mycol
union all select '... from schema1.table_2 ...'
)
select mycol, regexp_replace(mycol, '\sschema1\.(\w+_tmp)\s', ' \1 ') newcol from t
麦考尔 | 纽科尔 :-------------------------------- | :---------------------------- ...来自schema1.table_1_tmp ... | ...来自 table_1_tmp ... ... 从 schema1.table_2 ... | ...来自 schema1.table_2 ...
推荐阅读
- c++ - 如何使用 boost asio 库获取 async_connect?
- python - 使用 PdfPages python 将多个图保存为 pdf
- javascript - 来自lessc的源映射文件指向错误的less文件
- c++ - 如果将对象创建为另一个类的数据成员,如何将值传递给参数化构造函数?
- reactjs - 在 React Jest 中检查 blob 响应的测试用例
- javascript - 加载页面后将输入值复制到另一个输入
- corda - 我将如何存储 LinearState 的版本/序列号?
- deployment - 在“本地”服务器(具有外部访问权限)上安全地部署 Dash 应用程序
- python - 查找二维列表中的所有匹配元素并将其替换为一个值
- php - 动态获取文件路径