使用 oracle regexp_replace 替换部分代码

using oracle regexp_replace to replace some part of a code

我有一些代码,我只想替换该代码的一部分。在我的情况下 BB 到 XX

AA/BB
AA/BB1
AA/BB-1
BB
BB1
BB-1

我尝试使用 regexp_replace 这个简单的表格

查询:

select regexp_replace('AA/BB','BB','XX') from dual; 

结果:

AA/XX

查询:

select regexp_replace('AA/BB-1','BB','XX') from dual; 

结果:

AA/XX-1

它工作正常,但在斜杠 AA 之前也可能是 BB,但这次它不应该被替换,但仍然适用于其余代码。

select regexp_replace('BB/BB','BB','XX') from dual; 

当然给了我XX/XX,但我想达到BB/XX等等

也许我们可以这样表述:替换 'BB' 后面没有跟 '/'?

regexp_replace(myval, 'BB($|[^/])', 'XX')

Demo on DB Fiddle:

with t as (
    select 'AA/BB' myval from dual 
    union all select 'AA/BB1' from dual
    union all select 'AA/BB-1' from dual
    union all select 'BB' from dual
    union all select 'BB' from dual
    union all select 'BB1' from dual
    union all select 'BB-1' from dual
    union all select 'BB/BB' from dual
)
select myval, regexp_replace(myval, 'BB($|[^/])', 'XX') newval from t
MYVAL   | NEWVAL 
:------ | :------
AA/BB   | AA/XX  
AA/BB1  | AA/XX1 
AA/BB-1 | AA/XX-1
BB      | XX     
BB      | XX     
BB1     | XX1    
BB-1    | XX-1   
BB/BB   | BB/XX  

或者 - 请参阅代码中的注释,其中“从位置开始”读作:如果那里有超过 1 个 BB 子字符串,则从 [= 中第二个 BB 的位置开始13=]。否则,从MYVAL.

开头开始

感谢@GMB 提供示例数据。

SQL> with t as (
  2      select 'AA/BB' myval from dual
  3      union all select 'AA/BB1' from dual
  4      union all select 'AA/BB-1' from dual
  5      union all select 'BB' from dual
  6      union all select 'BB' from dual
  7      union all select 'BB1' from dual
  8      union all select 'BB-1' from dual
  9      union all select 'BB/BB' from dual
 10      union all select 'AA/BB/BB-2' from dual
 11  )
 12  select myval,
 13         regexp_replace
 14           (myval,             --> in MYVAL
 15            'BB',              --> replace BB
 16            'XX',              --> with XX
 17            case when regexp_count(myval, 'BB') = 1 then 1  --> starting at position*
 18                 else instr(myval, 'BB', 1, 2)
 19            end
 20           ) result
 21  from t;

MYVAL      RESULT
---------- ---------------
AA/BB      AA/XX
AA/BB1     AA/XX1
AA/BB-1    AA/XX-1
BB         XX
BB         XX
BB1        XX1
BB-1       XX-1
BB/BB      BB/XX
AA/BB/BB-2 AA/BB/XX-2

9 rows selected.

SQL>