Matching consecutive digits REGEXP_REPLACE in Redshift

自作多情 提交于 2019-12-13 15:58:30

问题


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!


回答1:


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,'




回答2:


Here you go. 😀

SELECT regexp_replace('16,16,16,3,3,4,16,16,', '([0-9]+,){2}', '$1') ;

 regexp_replace
----------------
 16,3,4,16,


来源:https://stackoverflow.com/questions/54084967/matching-consecutive-digits-regexp-replace-in-redshift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!