首页 > 解决方案 > 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字符串。

标签: sqlregexpostgresqlreplaceregexp-replace

解决方案


你可以使用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

当字符串与正则表达式匹配时,匹配表达式被替换为:一个空格,然后是捕获的部分,然后是另一个空格。

DB Fiddle 上的演示

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 ...

推荐阅读