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

前端 未结 7 1210
闹比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条回答
  •  梦毁少年i
    2021-01-11 20:41

    Another way to count last position is to slit string to array by delimeter equals to needed character and then substract length of characters for the last element from the length of whole string

    CREATE FUNCTION last_pos(char, text) RETURNS INTEGER AS
    $$
    select length($2) - length(a.arr[array_length(a.arr,1)]) 
    from (select string_to_array($2, $1) as arr) as a
    $$ LANGUAGE SQL;
    

    For the first position it is easier to use

    select position('#' in '2010-####-3434');
    

提交回复
热议问题