开发者

Postgresql: Remove last char in text-field if the column ends with minus sign

I want to remove the last char in a column if it ends with the minus sign. How c开发者_开发知识库ould I do this in postgresql?

For example:

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

Is there an easy syntax I can use?


Use the trim function if all trailing dashes can be removed, or use regexp_replace if you need only the last dash removed. Trim probably performs 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜