Return PostgreSQL 字符串中第二次出现之前的所有内容

Return everything before 2nd occurrence in a string in PostgreSQL

我想 return 在 PostgreSQL 中第 2 次出现字符斜杠“/”(如果有)之前的所有字符。

输入列:

/apple/orange/banana
/
/mango
/avocado/kiwi

所需的输出列:

/apple
/
/mango
/avocado

有人可以帮忙吗?

一种方法是regexp_replace():

select t.*,
       regexp_replace(col, '^([^/]*/[^/]*)/.*$', '')
from t;

Here 是一个 db<>fiddle.

您可以将 substring() 与正则表达式一起使用:

select substring(the_column from '(/\w*)')
from the_table

另一种选择是 split_part()

select '/'||split_part(the_column, '/', 2)
from data