【问题标题】:Regular expression replace a string pattern正则表达式替换字符串模式
【发布时间】:2019-11-12 13:43:01
【问题描述】:

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

在 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

【问题讨论】:

    标签: sql regex replace


    【解决方案1】:

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

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

    live demo


    测试:

    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
    

    【讨论】:

      【解决方案2】:

      如果你对案件不是特别清楚,你可以使用它

      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(lower(iD),'[^a-z]+(inc)([^a-z])*','') 
      from T
      

      输出:

        id        regexp_replace
      Cincin,Inc  cincin
      Tinc, INc.  tinc
      Cloud       cloud
      Dinct Inc.  dinct
      

      【讨论】:

        【解决方案3】:

        尝试替换模式,?\s*Inc\.?$

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

        【讨论】:

        • 它不适用于记录 - Tinc, INc。 Dict Inc.
        • 那么你想在这种情况下作为输出吗?
        • 想要删除所有以 ',Inc' ' , Inc' ' , Inc.' 结尾的记录的 INC '公司'如果可能,不区分大小写的模式 INC 或 inc 或 InC 等...代码中提到的 O/P-Cincin Tinc Cloud Dict
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-13
        • 2017-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多