Matching consecutive digits REGEXP_REPLACE in Reds

2019-07-21 08:52发布

I'm trying to remove consecutive numbers from a string in Redshift.

From '16,16,16,3,3,4,16,16,' I want to get '16,3,4,16,'.

The following construction doesn't work for me:

SELECT regexp_replace('16,16,16,3,3,4,16,16,', '(.+)\1{1,}', '\1');

It's returning exactly the same string. :(

Thanks!

2条回答
聊天终结者
2楼-- · 2019-07-21 09:20

Here you go.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-21 09:36

Here is the answer using a Redshift python UDF.

create or replace function dedupstring(InputStr varChar)
  returns varchar
stable
as $$
    OutputStr=''
    PrevStr=''
    first=True
    for part in InputStr.split(','):
        if part <> PrevStr:
            if first:
                OutputStr+=part
            else:
                OutputStr+=','+part
            PrevStr=part
            first=False
    return OutputStr
$$ language plpythonu;

Select dedupstring('16,16,16,3,3,4,16,16,');

This returns '16,3,4,16,'

查看更多
登录 后发表回答