【问题标题】:remove the last two spaces from a string从字符串中删除最后两个空格
【发布时间】:2020-03-18 00:40:24
【问题描述】:

如果我的字符串长度为 30。我必须从字符串中删除最后 2 个空格。

如果我的字符串长度是 29。我必须从字符串中删除最后一个空格。

例如。 COADC Cathy & Ralph Ward Jr 73 应该是 COADC Cathy & Ralph WardJr73
而不是COADCCathy&RalphWardJr73

尝试了trim()instrsubstrreplace() 空格,但没有成功。还有其他功能吗?

【问题讨论】:

  • 我不太明白这样做的目的是什么。字符串的长度(30 对 29 个字符)意味着什么,为什么这会改变您从字符串中删除 1 或 2 个空格的决定?
  • 我使用的工具在字符串超过 28 个字符时无法正确显示列

标签: sql oracle replace


【解决方案1】:

您仍然可以使用regexp_replace()。在这种情况下,逻辑是:

select regexp_replace(str, ' ([^ ]+) ([0-9]+)$', '\1\2')
from (select 'COADC Cathy & Ralph Ward Jr 73' as str from dual union all
      select 'COADC Cathy & Ralph Ward Jr 73x' as str from dual 
     ) x;

正则表达式匹配两个由空格分隔的模式。最后一个仅由数字组成,并且必须位于字符串的末尾。前一个由任何非空格字符组成。替换删除了中间空间。

Here 是一个 dbfiddle。

【讨论】:

  • 谢谢。你能解释一下代码吗?我可以理解正则表达式在字符串末尾搜索模式。 ([^ ]+) 搜索空格?
【解决方案2】:

我会为此创建一个函数:

create function reducestr
    (str in varchar2,
     len in number,
     sp in varchar2 := ' '
    ) return varchar2 is
    pos number;
    buf varchar2(4000);
begin
    buf := trim(sp from str);
    loop
        if length(buf) <= len then
            -- great, we're already at or under the target length
            return buf;
        else
            -- find the position of the last occurrence of a space
            pos := instr(buf, sp, -1);
            if pos = 0 then
                -- no more spaces to remove, just truncate the string
                return substr(buf, 1, len);
            else
                -- remove the last space
                buf := substr(buf, 1, pos-1) || substr(buf, pos+1);
            end if;
        end if;
    end loop;
end reducestr;

select reducestr('COADC Cathy & Ralph Ward Jr 73',28) from dual;

COADC Cathy & Ralph WardJr73

【讨论】:

    【解决方案3】:

    应该这样做:

    declare @String as varchar(100)
    
    Set @String = 'COADC Cathy & Ralph Ward Jr 73'
    
    declare @ReverseString as varchar(100)
    declare @ResultString as varchar(100)
    declare @ReverseResult as varchar(100)
    set @ReverseString = REVERSE(@String)
    
    select @ReverseString
    
    SELECT @ReverseResult = STUFF(@ReverseString, CHARINDEX(' ', @ReverseString), 1, '')
    
    if len(@String) = 30
        select @ReverseResult = STUFF(@ReverseResult, CHARINDEX(' ', @ReverseResult), 1, '')
    if len(@String) = 29
        select @ReverseResult = @ReverseResult
    
    select reverse(@ReverseResult)
    

    告诉我进展如何

    【讨论】:

    • 我正在使用 sql developer 。它不支持 stuff()
    猜你喜欢
    • 2016-01-21
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2013-07-28
    • 1970-01-01
    相关资源
    最近更新 更多