在Oracle中提取子字符串

时间:2019-08-03 14:17:48

标签: sql string oracle substring

假设我有三行,值为

1 121/2808B|:6081
2 OD308B|:6081_1:
3 008312100001200|:6081_1

我只想显示值,直到B,但想排除B之后的所有内容。因此,如您在上述数据中所见:

  • 来自121/2808B|:6081的我只想要121/2808B
  • 仅来自OD308B|:6081_1:的{​​{1}}
  • 仅来自OD308B的{​​{1}}。

感谢帮助。

4 个答案:

答案 0 :(得分:2)

尝试以下操作:regexp_substr('<Your_string>','[^B]+')

SELECT
    REGEXP_SUBSTR('121/2808B|:6081', '[^B]+')
FROM
    DUAL;

REGEXP_S
--------
121/2808



SELECT
    REGEXP_SUBSTR('OD308B|:6081_1:', '[^B]+')
FROM
    DUAL;

REGEX
-----
OD308


SELECT
    REGEXP_SUBSTR('008312100001200.', '[^B]+')
FROM
    DUAL;

REGEXP_SUBSTR('0
----------------
008312100001200.

db<>fiddle demo

干杯!

答案 1 :(得分:2)

您可以尝试使用SUBSTR()和INSTR()

select   SUBSTR('121/2808B|:6081',1,INSTR('121/2808B|:6081','B', 1, 1) -1) 
from DUAL 

答案 2 :(得分:2)

我想您忘了提到您想使用|作为字段分隔符,但是我从第三个字符串的预期结果中得出了这一点。因此,以下内容应为您提供所需的东西:

WITH cteData AS (SELECT 1 AS ID, '121/2808B|:6081' AS STRING FROM DUAL UNION ALL
                 SELECT 2, 'OD308B|:6081_1:' FROM DUAL UNION ALL
                 SELECT 3, '008312100001200|:6081_1' FROM DUAL)
SELECT ID, STRING, SUBSTR(STRING, 1, CASE
                                       WHEN INSTR(STRING, 'B') = 0 THEN INSTR(STRING, '|')-1
                                       ELSE INSTR(STRING, 'B')-1
                                     END) AS UP_TO_B
  FROM cteData;

dbfiddle here

答案 3 :(得分:0)

假设鲍勃·贾维斯(Bob Jarvis)在“ |”的假设下是正确的也是一个定界符(似乎很可能),尝试:

-- define test data
with test as
     ( select '121/2808B|:6081' stg     from dual union all
       select 'OD308B|:6081_1:'         from dual union all
       select '008312100001200|:6081_1' from dual
    ) 
-- execute extract
select regexp_substr(stg , '[^B|]+') val
  from test ;