首页 > 解决方案 > 正则表达式替换字符串模式

问题描述

我正在尝试检查从列中排除字符串模式的最佳和最佳方法,而不影响实际数据。

在 Redshift DW 中,我有表列 company,其中某些记录以不同的方式以 INC 结尾,因此希望排除 INC 的字符串模式并仅捕获公司名称。请参阅下面的示例数据和预期输出。

WITH T AS (
    select 'Cincin,Inc' id
    union all
    select 'Tinc, INc.' id 
    union all
    select 'Cloud' id 
    union all
    select 'Dinct Inc.' id 
)

select id , regexp_replace(id,{exp}) from T


/**OutPut***/
Cincin
Tinc
Cloud
Dinct

标签: sqlregexreplace

解决方案


Redshift 不支持正则表达式不区分大小写,但鉴于您的目标字符串很小,您可以使用以下方法解决它而不会带来太多痛苦[Ii][Nn][Cc]

regexp_replace(id, ',? *[Ii][Nn][Cc]\.?$', '')

现场演示


测试:

WITH T AS (
    select 'Cincin,Inc' id
    union all
    select 'Tinc, INc.' id 
    union all
    select 'Cloud' id 
    union all
    select 'Dinct Inc.' id 
)    
select id , regexp_replace(id, ',? *[Ii][Nn][Cc]\.?$', '') from T

输出:

Cincin
Tinc
Cloud
Dinct

推荐阅读