Postgresql: remove the last char in the text box if the column ends with a minus sign

I want to remove the last char in the column if it ends with a minus sign. How can I do this in postgresql?

For example:

sdfs-dfg4t-etze45z5z- => sdfs-dfg4t-etze45z5z gsdhfhsfh-rgertggh => stay untouched 

Is there a simple syntax that I can use?

+8
sql postgresql
source share
2 answers

Use the trim function if you can delete all trailing dashes or use regexp_replace if you need only the last dash. Trim probably works better than regexp_replace.

 with strings as ( select 'sdfs-dfg4t-etze45z5z-' as string union all select 'sdfs-dfg4t-etze45z5z--' as string union all select 'gsdhfhsfh-rgertggh' ) select string, trim(trailing '-' from string) as all_trimmed, regexp_replace(string, '-$', '') as one_trimmed from strings 

Result:

 string all_trimmed one_trimmed sdfs-dfg4t-etze45z5z- sdfs-dfg4t-etze45z5z sdfs-dfg4t-etze45z5z sdfs-dfg4t-etze45z5z-- sdfs-dfg4t-etze45z5z sdfs-dfg4t-etze45z5z- gsdhfhsfh-rgertggh gsdhfhsfh-rgertggh gsdhfhsfh-rgertggh 
+13
source share

use regexp_replace(your_field, '-+$', '');

+4
source share

Source: https://habr.com/ru/post/650205/


All Articles