PostgreSQL – Split and get last part of a string in plpgsql

This function written in plpgsql splits the string according to the separator and returns the last part. If the separator is not present in the string this function returns an empty string.

 CREATE OR REPLACE FUNCTION public.get_last_part(text, text)
    RETURNS SETOF text
    LANGUAGE plpgsql
    AS $function$
    DECLARE 
      pos int; 
      last_pos int; 
      delim_length int := length($2);
      empty_string character := '';

    BEGIN

        pos := strpos($1, $2);
        IF pos > 0 THEN
          last_pos := length($1)- length(regexp_replace($1, E'.*\\' || $2,''));
          RETURN NEXT substring($1 FROM last_pos + 1);
        ELSE
          RETURN NEXT empty_string;
          
        END IF; 

      RETURN;
    END;
 $function$
SELECT get_last_part('dotmaui.com','.') -- returns 'com'
SELECT get_last_part('dotmaui.min.js','.') -- returns 'js'
SELECT get_last_part('dotmaui,is,cool',',') -- returns 'cool'
SELECT get_last_part('dotmaui',',') -- returns ''

Leave a Comment

Your email address will not be published. Required fields are marked *