I have a text like this:
'a:b:c:d'
I would like to ignore the last part of the split text, my result should be
'a:b:c'
I tried split_part
on it, but it doesn’t work, neither applying reverse at it.
Queries I tried and didn’t worked:
select split_part('a:b:c:d', ':', 1);
select reverse(split_part(reverse('a:b:c:d'), ':', -1));
5
Answers
You can use
substring
and find the last : in the stringfiddle
Use a
substring()
with a regular expression: demoWhich is looking for two sets of non-colon characters that end with a colon, then then one such set after that. It uses POSIX syntax
^
at the beginning, outside square brackets, means you start at the beginning[^:]
means any character except a colon.
means any character, at all*
means any amount of the previous thing[^:]*
means any amount of that anything, except a colon[^:]*:
means the same, followed by an actual colon([^:]*:){2}
means the same, just repeated twiceSince PostgreSQL arrays support subscripts and slices, you can also split the text into an array, use a
[:3]
to get your first 3 elements, then reassemble the text:You can also do it your own way:
This spots the position of the first colon in reversed version of the text, saves only what comes after that first colon, then reverses it back again.
With only one example, your goal is ambiguous. The following query demonstrates approaches using regular expressions to keep only the portion with the first
n
fields, or all but the last field:Running this query produces the following output:
You can use the SQL query below to ignore the final character of a text string in PostgreSQL, such as changing ‘a:b:c:d’ into ‘a:b:c’. This command basically removes the last section of the text by extracting a substring from the original string .
If you indeed want to "ignore after n-th character", like the title says, just use
left()
: