Postgresql:如果列以减号结尾,则删除文本字段中的最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4461891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Postgresql: Remove last char in text-field if the column ends with minus sign
提问by Chris
I want to remove the last char in a column if it ends with the minus sign. How could I do this in postgresql?
如果以减号结尾,我想删除列中的最后一个字符。我怎么能在 postgresql 中做到这一点?
For example:
例如:
sdfs-dfg4t-etze45z5z- => sdfs-dfg4t-etze45z5z
gsdhfhsfh-rgertggh => stay untouched
Is there an easy syntax I can use?
有我可以使用的简单语法吗?
回答by Jeremy Shimanek
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.
如果可以删除所有尾随破折号,请使用修剪功能,如果您只需要删除最后一个破折号,请使用 regexp_replace。Trim 的性能可能比 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
回答by Chris
use regexp_replace(your_field, '-+$', '');
用 regexp_replace(your_field, '-+$', '');