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

前端 未结 7 1162
闹比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:49

    This pure SQL function will provide the last position of a char inside the string, counting from 1. It returns 0 if not found ... But (big disclaimer) it breaks if the character is some regex metacharacter ( .$^()[]*+ )

    CREATE FUNCTION last_post(text,char) RETURNS integer AS $$ 
         select length($1)- length(regexp_replace($1, '.*' || $2,''));
    $$ LANGUAGE SQL IMMUTABLE;
    
    test=# select last_post('hi#-#-#byte','#');
     last_post
    -----------
             7
    
    test=# select last_post('hi#-#-#byte','a');
     last_post
    -----------
             0
    

    A more robust solution would involve pl/pgSQL, as rfusca's answer.

提交回复
热议问题