I am hitting a SQL query below and resulting as show below.
SELECT column from Table LIMIT =1
GLOBE-WORLD-AIRPORT-Azerbaijan-country-SECRET-ABORT
Here I want to get the data Azerbaijan-country
as my result. My logic should fetch the content after the third – and the second – from the last. So that I can get the required result. How to do this in PostgreSQL.
2
Answers
You can use
regexp_substr()
in PostgreSQL 15+: demo at db<>fiddleYou can read more on pattern matching in PostgreSQL in the doc.
[^-]
means any character except a hyphen.([^-]*-)
means any amount of non-hyphens followed by a hyphen.([^-]*-){3}
means 3 repetitions of that. This is looking for your initial three hyphens and anything they separate.(.*)
is any amount of any character. This is what you want to catch(-[^-]*)
is a hyphen followed by any amount of non-hyphens.(-[^-]*){2}
looks for two of those after your target.1, 1, 'i', 2
mean (in this order) that you want to(.*)
.In earlier versions all the way back to 9.4, you can use
regexp_replace()
to wipe everything around your target: demoThis uses
^
outside[]
as beginning of line idicator and$
as end of line indicator.There Some doubts about used RDBMS.
I will offer a solution without using regexp.
Output is
from test data
string_to_table actual from postgresql 14.