Reputation: 149
I want to split the string in MySQL query using a delimiter. However, I want to split on the last occurrence of the string and get the first part of the string.
For example:-
'apple - banana - grape'
The result after splitting should be 'apple - banana'. The important thing is that we do not know how many occurrences of '-' will be there in the string.
Upvotes: 0
Views: 724
Reputation: 520908
On MySQL 8+, the REGEXP_REPLACE
function works well for your requirement:
SELECT fruits, REGEXP_REPLACE(fruits, '\\s*-\\s*[^-]+$', '') AS fruits_out
FROM yourTable;
By the way, a much better table design would be to store each CSV fruit value in a separate row. This would alleviate the need to use regex to manipulate the list of fruits.
Upvotes: 1