【问题标题】:Use postgres regexp_replace() to replace integers in a string使用 postgres regexp_replace() 替换字符串中的整数
【发布时间】:2019-09-16 16:38:05
【问题描述】:

我有一个需要查询的 redshift 数据库,并且需要将相似的字符串组合在一起。我正在使用 regexp_replace() 来执行此操作,但无法弄清楚如何将中间有整数的字符串分组。例如:

数据集:

string
'aaa/123/bbb'
'aaa/456/bbb'
'ccc/123/ddd'

我需要将其分组以便我们得到

string     count(*)
aaa/id/bbb 2
ccc/id/ddd 1

所以我尝试过使用

regexp_replace(endpoint, '/[0-9]+$/', '/id/')

但它不起作用,我假设是因为没有通配符之类的?但我不知道如何解决这个问题。

提前致谢

【问题讨论】:

    标签: sql regex amazon-redshift


    【解决方案1】:

    我知道您还想替换最后的数字。这接近你想要的:

    select regexp_replace(endpoint, '/[0-9]+(/|$)', '/id/')
    from (select 'aaa/123/bbb' as endpoint union all
          select 'aaa/123' as endpoint 
          ) x
    

    但在第二种情况下,它会在末尾返回一个斜杠。

    如果你没有其他以数字开头的中间值,那么这就是你想要的:

    select regexp_replace(endpoint, '/[0-9]+', '/id')
    from (select 'aaa/123/bbb' as endpoint union all
          select 'aaa/123' as endpoint 
          ) x
    

    否则,两次调用 regexp_replace() 就可以解决问题:

    select regexp_replace(regexp_replace(endpoint, '/[0-9]+/', '/id/'), '/[0-9]$', '/id')
    from (select 'aaa/123/bbb' as endpoint union all
          select 'aaa/123' as endpoint 
          ) x;
    

    【讨论】:

      猜你喜欢
      • 2013-11-02
      • 2014-11-17
      • 2021-12-29
      • 2012-09-25
      • 2018-11-23
      • 2015-09-11
      • 2015-03-12
      • 2013-10-25
      • 2015-04-26
      相关资源
      最近更新 更多