Oracle RTRIM 削减了比要求的更多

Oracle RTRIM trims more than asked for

有谁知道为什么会这样:

SELECT RTRIM('123R_CLUSTER', '_CLUSTER') -- should give '123R' 
FROM DUAL;
SELECT RTRIM('123S_CLUSTER', '_CLUSTER') -- should give '123S' 
FROM DUAL;
SELECT RTRIM('123T_CLUSTER', '_CLUSTER') -- should give '123T'
FROM DUAL;
SELECT RTRIM('123U_CLUSTER', '_CLUSTER') -- should give '123U'
FROM DUAL;

return '123' 而不是预期的?

我正在使用 Oracle Database 12c 企业版 12.1.0.2.0 版 - 64 位生产版。

当您尝试这些时,乐趣就开始了:

文档写的很清楚:

The Oracle/PLSQL RTRIM function removes all specified characters from the right-hand side of a string.

所以它不会删除字符串末尾的 string _CLUSTER - 它会删除字符,直到有一个不是 _、C、 L、U、S、T、E 或 R。由于您的后缀是 R/S/T/U,它们也符合 rtrim 条件,因此被删除。例如 123S_SLURTE

作为一个更容易理解的例子,

rtrim('LK_123aababaabbbababbaa', 'ab') // returns LK_123

rtrim 根本不是手头工作的工具:)

如果您想知道如何轻松地做到这一点,试试这个:

SELECT regexp_substr('123R_CLUSTER', '^(.*)_CLUSTER$', 1, 1, null, 1) from dual
union all
SELECT regexp_substr('123S_CLUSTER', '^(.*)_CLUSTER$', 1, 1, null, 1) from dual
union all
SELECT regexp_substr('123T_CLUSTER', '^(.*)_CLUSTER$', 1, 1, null, 1) from dual
union all
SELECT regexp_substr('123U_CLUSTER', '^(.*)_CLUSTER$', 1, 1, null, 1) from dual;

产量

REGEXP_SUBST
------------
123R
123S
123T
123U

以及解密函数

regexp_substr(
     '123T_CLUSTER',    -- source_field
     '^(.*)_CLUSTER$',  -- regular expression 
                        -- to capture all characters from start of
                        -- data up to "_CLUSTER"
     1,                 -- start looking at position 1 of string
     1,                 -- which occurance to return
     null,              -- used for match behaviour
     1)                 -- return what is in first set of parentheses