问题
I want to replace instances of the word OF with "OF". I only want this to work on complete words. So not on L_OF, DOF, OFZ, DOFD, OF_L, etc.
My code works below except for the final string.
It returns:
("OF"*OF + 2)
... instead of:
("OF"*"OF" + 2)
How can I get it to work on that one as well?
with stg as
(
select '(ofof+ol)' str from dual union all
select '(oof+ol+of)' from dual union all
select '(*of + 2)' from dual union all
select '(of*of + 2)' from dual
)
select str,
regexp_replace(upper(str), '(\W|^)(OF)(\W|$)', '\1"OF"\3') as str2
from stg
回答1:
Here's one way to do this - with a recursive query (requires Oracle 11.2 or higher). Don't expect it to be fast.
with stg as
(
select '(ofof+ol)' str from dual union all
select '(oof+ol+of)' from dual union all
select '(*of + 2)' from dual union all
select '(of*of + 2)' from dual
),
rec ( str, lvl, new_str ) as
(
select str, 1, upper(str)
from stg
union all
select str, lvl + 1,
regexp_replace(new_str, '(\W|^)(OF)(\W|$)', '\1"OF"\3', 1, lvl)
from rec
where regexp_instr(new_str, '(\W|^)(OF)(\W|$)', 1, lvl) > 0
)
select str, new_str
from rec
where regexp_instr(new_str, '(\W|^)(OF)(\W|$)', 1, lvl) = 0
;
STR NEW_STR
------------ ------------------
(ofof+ol) (OFOF+OL)
(oof+ol+of) (OOF+OL+"OF")
(*of + 2) (*"OF" + 2)
(of*of + 2) ("OF"*"OF" + 2)
回答2:
This is too long for a comment. I don't know the solution, but I do understand the problem. You will see it much easier with 'of of'
but not with 'of**of'
.
The problem is that the character that defines the first word is not used for defining the second word. Regular expressions seem to need a special character such as "^" to mean "first character after previous match". I don't know if one exists.
来源:https://stackoverflow.com/questions/44552990/oracle-regexp-replace-on-complete-words