在PostgreSQL中获取2个字符之间的子串

时间:2018-03-01 18:47:19

标签: sql postgresql

我试图在postgreSQL中获取像这样的URL之间的字符:

  

www.abc.com/hello/xyz

     

www.abc.com/hi/pqr

     

www.abc.com/yellow/xyz

我想要

  

您好

     

     

这是我到目前为止所做的:

select distinct substring(url, position('/' in url)+ 1) theURL from table;

我只能得到第一个" /"

我不知道如何获得第二个位置

3 个答案:

答案 0 :(得分:1)

一种方法使用regexp_split_to_array()

select (regexp_split_to_array(url, '/'::text))[2]

或者更好,因为@NeilMcGuigan建议:

select split_part(url, '/', 2)

答案 1 :(得分:0)

遵循子字符串方法,并使用第一个子字符串结果进行第二次搜索:

select distinct substring(
  substring(url, position('/' in url)+ 1)
  , 0
  , position('/' in substring(url, position('/' in url)+ 1))) AS theURL 
from table;

查询的基本操作是使用substring的原始结果来启动搜索下一个\,这样就可以将文本保留在前两个\

之间

如果按字母顺序排序很重要,可以添加外部查询:

SELECT theURL FROM (
select distinct substring(
  substring(url, position('/' in url)+ 1)
  , 0
  , position('/' in substring(url, position('/' in url)+ 1))) AS theURL 
from table
) AS xt
ORDER BY xt.theURL;

答案 2 :(得分:0)

以下查询甚至可用于www.abc.com/hello

等输入
SELECT DISTINCT (regexp_matches(url, '/([^/]+)'))[1] theURL
FROM table;

并且它将跳过空条目