【问题标题】:How to get substring from 4th occurence of a character until the end of given string in PSQL如何从第 4 次出现的字符到 PSQL 中给定字符串的结尾获取子字符串
【发布时间】:2017-08-11 18:14:06
【问题描述】:

例子

我有一个字符串...

'/this/is/a/given/string/test.file'.

如何在 PSQL 中获取子字符串 'given/string/test.file'?

谢谢!

【问题讨论】:

    标签: postgresql substring psql


    【解决方案1】:

    你可以使用正则表达式

    with example(str) as (
        values('/this/is/a/given/string/test.file')
    )
    
    select regexp_replace(str, '(/.*?){4}', '')
    from example;
    
         regexp_replace     
    ------------------------
     given/string/test.file
    (1 row) 
    

    或函数string_to_array()

    select string_agg(word, '/' order by ord)
    from example,
    unnest(string_to_array(str, '/')) with ordinality as u(word, ord)
    where ord > 4;
    

    另请阅读How to find the 3rd occurrence of a pattern on a line

    【讨论】:

      【解决方案2】:

      我不知道如何获取子字符串的第 n 次出现,但是对于这个问题,您可以使用正则表达式。像这样:

      select substring('/this/is/a/given/string/test.file' from '/[^/]+/[^/]+/[^/]+/(.*)')
      

      您可以改进正则表达式,这仅用于演示目的。

      【讨论】:

        猜你喜欢
        • 2012-01-05
        • 2020-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多