I need to create a query using the SUBSTRING function in Postgresql 9.x to extract a substring between a string and first pipe occurrence.
My source string is something like this:
THIS IS MY EXAMPLE|OTHER EXAMPLE|HELLO: Kevin|OTHER EXAMPLE|OTHER EXAMPLE
So I created this query:
SELECT SUBSTRING(myField from 'HELLO: (.*)\|') AS test FROM myTable
to get the word Kevin between the string 'HELLO: ' and the first occurrence of character pipe, but it doesn't work as intended because it returns Kevin|OTHER EXAMPLE|OTHER EXAMPLE.
Where am I going wrong?
HELLO: ([^|]+), likeSELECT SUBSTRING(myField from 'HELLO: ([^|]+)') AS test FROM myTable*is greedy. You can use its non-greedy (lazy) counterpart:*?, like'HELLO: (.*?)\|'(which works in PostgreSQL too). (And of course the posted answer is right too, you can get around greediness with altering the pattern logic too.)