Oracle Regexp_Substr或Regexp_Replace查询,未满足所有情况

时间:2019-03-06 17:34:21

标签: sql oracle

我正在使用Oracle 12c R1 我想提取字符串的前两个部分,最后一个包含X

  Input : 'AB12,AB23,AB50,AB71X,AB43,AB98X,AB11'
    Expected Output :  AB12,AB23,AB98

尝试了以下内容

  SELECT REGEXP_REPLACE('AB12,AB23,AB50,AB71X,AB43,AB98X,AB11','(.{9}).*(,.{4})X(.+$)?','\1\2) col1 FROM dual;

但是无法正确获得下面字符串的X部分

  'AB12X,AB23X,AB50X,AB71,AB43'   Expected Output => AB12,AB23,AB50
                                  Output => AB12X,AB2,AB50

  'AB12,AB23X'                    Expected Output => AB12,AB23
                                  Output => AB12,AB23X

3 个答案:

答案 0 :(得分:2)

无需正则表达式。您可以将instr与th_appearance = -1一起使用,从头开始

  with t as (select 'AB12,AB23,AB50,AB71X,AB43,AB98X,AB11' as input from dual)
  select 
  substr(input,1, instr(input,',', 1)-1) as firstPart,
  substr(input,instr(input,',', 1)+1, instr(input,',', 1, 1)-1) as secondPart,
  substr(substr(input,1, instr(input,'X,', -1)-1), instr(substr(input,1, instr(input,'X,', -1)), ',', -1)+1) as thirdPart
  from t;

返回:

 AB12   AB23    AB98

或串联:

 with t as (select 'AB12,AB23,AB50,AB71X,AB43,AB98X,AB11' as input from dual)
  select 
  substr(input,1, instr(input,',', 1)-1) || ',' ||
  substr(input,instr(input,',', 1)+1, instr(input,',', 1, 1)-1)  || ',' ||
  substr(substr(input,1, instr(input,'X,', -1)-1), instr(substr(input,1, instr(input,'X,', -1)), ',', -1)+1) as output
  from t;

返回:

AB12,AB23,AB98

答案 1 :(得分:1)

此查询可以帮助您

`head`'s interval does not overlap `segment`
    no action
`head`'s interval contains `segment`
    remove segment
`segments`'s interval contains `head` (both ends stick out
    split segment into the two remaining pieces.
`head`'s interval overlaps one end of `segment`
    truncate segment

答案 2 :(得分:0)

尝试一下:

select regexp_replace('AB12,AB23,AB50,AB71X,AB43,AB98X,AB11', '^(.{4},.{4}),.*,(.{4})X.*$', '\1,\2')
from dual;