如何在 PSQL 中获取从第 4 次出现的字符到给定字符串结尾的子字符串

How to get substring from 4th occurence of a character until the end of given string in PSQL

例子

我有一个字符串...

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

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

谢谢!

您可以使用正则表达式

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

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

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

您可以改进正则表达式,这只是为了演示目的。