strposrev

From PostgreSQL wiki

Jump to: navigation, search

Library Snippets

strposrev(text,text)

Works with PostgreSQL

9.1

Written in

PL/pgSQL

Depends on

Nothing


The string function strposrev(instring text, insubstring text) returns the position of a substring within a string, starting from the end, reverse to the built in strpos(text,text) function. It is like the instrrev() function known from vb, or the string.lastindexof() method known from java and csharp.

CREATE OR REPLACE FUNCTION strposrev(instring text, insubstring text)
  RETURNS INTEGER AS
$BODY$
  DECLARE result INTEGER;
  BEGIN
    IF strpos(instring, insubstring) = 0 THEN
      -- no match
      result:=0;
    ELSEIF LENGTH(insubstring)=1 THEN
      -- add one to get the correct position from the left.
      result:= 1 + LENGTH(instring) - strpos(REVERSE(instring), insubstring);
    ELSE 
      -- add two minus the legth of the search string
      result:= 2 + LENGTH(instring)- LENGTH(insubstring) - strpos(REVERSE(instring), REVERSE(insubstring));
    END IF;
    RETURN result;
  END;
$BODY$
  LANGUAGE plpgsql IMMUTABLE STRICT
  COST 4;

see also

Personal tools