我想替換'|' 和 '_'。替換應該從第 nn 個字符開始并替換 n 次。例如
ABC|1234|mno|p|q|r|456|XYZ|QRS|TUV ====> ABC|1234|mno|p_q_r|456|XYZ|QRS|TUV
在上面的例子中 nn=14 和 n=3
到目前為止,我已經嘗試過了,但沒有得到預期的結果
SELECT REGEXP_REPLACE('ABC|1234|mno|p|q|r|456|XYZ', '[|]', '_',14) rep_str FROM DUAL
uj5u.com熱心網友回復:
在您的簡單示例中,指定這兩種情況更容易:
regexp_replace(
str
, '\|([^|] )'
||'\|([^|] )' -- 2 times just to make it more readable
||'(.*)' -- others
,'_\1_\2\3'
,14
)
帶有測驗資料的完整示例:DBFiddle
with t as (
select
'ABC|1234|mno|p|q|r|456|XYZ|QRS|TUV' str
,'ABC|1234|mno|p_q_r|456|XYZ|QRS|TUV' chk
from dual
)
select
str,chk,
regexp_replace(
str
, '\|([^|] )'
||'\|([^|] )' -- 2 times just to make it more readable
||'(.*)' -- others
,'_\1_\2\3'
,14
) as str2
from t
/
或者,如果您使它更可定制并更容易指定替換次數,您可以使用簡單的行內 pl/sql 函式和這樣的回圈:DBFiddle
with function regexp_replaces(
source_char varchar2
,pattern varchar2
,replace_char varchar2
,position int
,cnt int
) return varchar2
as
res varchar2(4000):=source_char;
begin
for i in 1..cnt loop
res:=regexp_replace(res,pattern,replace_char,position,1);
end loop;
return res;
end;
select
str,chk,
regexp_replaces(str,'\|','_',14,2) as str2
from t;
uj5u.com熱心網友回復:
你可以用普通的substr/來做instr,但需要仔細處理邊緣情況。提取您需要的零件并更換其中的所有管道。然后把所有東西放回去。
with -- function replace_n( str in varchar2, start_ in number, count_ in number ) return varchar2 as begin return /*Starting part unchanged*/ substr(str, 1, start_) /*Replacement: locate n'th - 1 occurrence of pipe*/ || translate( substr(str, start_ 1, instr(str, '|', start_, count_-1) - start_) , '|' , '_' ) /*Remaining string*/ || substr(str, instr(str, '|', start_, count_ - 1) 1) ; end; -- a(a) as ( select 'ABC|1234|mno|p|q|r|456|XYZ|QRS|TUV' from dual ) select replace_n(a, 14, 3) as res from a| 資源 | | :--------------------------------- | | ABC|1234|mno|p_q_r|456|XYZ|QRS|TUV |
db<>在這里擺弄
UPDn :或者如果您要從 position 開始替換大小的子字串nnn:
with -- function replace_n( str in varchar2, start_ in number, count_ in number ) return varchar2 as begin return /*Starting part unchanged*/ substr(str, 1, start_) /*Replacement: extract substring on size n*/ || translate( substr(str, start_ 1, instr(str, '|', start_, count_-1) - start_) , '|' , '_' ) /*Remaining string*/ || substr(str, instr(str, '|', start_, count_ - 1) 1) ; end; --
db<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437199.html
上一篇:在段落中搜索句子
