How to find the first and last occurrences of a specific character inside a string in PostgreSQL

前端 未结 7 1169
闹比i
闹比i 2021-01-11 20:26

I want to find the first and the last occurrences of a specific character inside a string. As an example, consider a string named \"2010-####-3434\", and suppose the charact

7条回答
  •  北荒
    北荒 (楼主)
    2021-01-11 20:52

    9.5+ with array_positions

    Using basic PostgreSQL array functions we call string_to_array(), and then feed that to array_positions() like this array_positions(string_to_array(str,null), c)

    SELECT
      arrpos[array_lower(arrpos,1)] AS first,
      arrpos[array_upper(arrpos,1)] AS last
    FROM ( VALUES
      ('2010-####-3434', '#')
    ) AS t(str,c)
    CROSS JOIN LATERAL array_positions(string_to_array(str,null), c)
      AS arrpos;
    

提交回复
热议问题