Extract last 4 characters from string? - Mailing list pgsql-general

From D. Dante Lorenso
Subject Extract last 4 characters from string?
Date
Msg-id 47604E96.6060505@lorenso.com
Whole thread Raw
Responses Re: Extract last 4 characters from string?
Re: Extract last 4 characters from string?
List pgsql-general
All,

Getting the first 4 characters from the begining of a string is easy enough:

   SELECT SUBSTR('ABCDEFGHIJKLMNOP', 1, 4);

Returns 'ABCD'.  But getting the last 4 characters appears to be a
little more work and is ugly:

   SELECT SUBSTR('ABCDEFGHIJKLMNOP', LENGTH('ABCDEFGHIJKLMNOP') - 3, 4);

Returns 'MNOP'.  I hate having to provide my input string more than once
like this.  So ... uglier:

   REGEXP_REPLACE('ABCDEFGHIJKLMNOP', '^.*(....)$', '\\1');

Returns 'MNOP'.  Many languages have a version of substr that takes
negative arguments to begin offset from the end of the string like this:

   SELECT SUBSTR('ABCDEFGHIJKLMNOP', -4);

That doesn't seem to work in PostgreSQL.  In fact, it doesn't even error
out ... it just returns the whole string.  Is there an easy (preferred)
  method that I'm missing?

-- Dante

pgsql-general by date:

Previous
From: Stephen Cook
Date:
Subject: Re: top posting
Next
From: "Ertel, Steve"
Date:
Subject: simple way to find the constraints