'Cut string after first occurrence of a character

I have strings like 'keepme:cutme' or 'string-without-separator' which should become respectively 'keepme' and 'string-without-separator'. Can this be done in PostgreSQL? I tried:

select substring('first:last' from '.+:')

But this leaves the : in and won't work if there is no : in the string.



Solution 1:[1]

regexp_replace() may be overload for what you need, but it also gives the additional benefit of regex. For instance, if strings use multiple delimiters.

Example use:

select regexp_replace( 'first:last', E':.*', '');

Solution 2:[2]

SQL Select to pick everything after the last occurrence of a character

select right('first:last', charindex(':', reverse('first:last')) - 1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 rchacko