Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

String manipulation with regexp_replace

BeantownAug 23 2022

I am working on some string manipulation, in the example below I am trying to replace all the ~ with A thru Z sequentially, depending on however many is needed up to Z.
In my code below, first I get the count of how many '1~' needs to be replaced, if it needs n replacements, then I loop n times. In each loop, I start with ascii 65 and increment by 1, and replace the ~ that exists at the nth occurrence in the string.
Not sure what I am doing wrong in the regexp_replace args, it is replacing ~ with A, B, C ... only in alternate occurrence, please see the example output.
Greatly appreciate any help!

declare
 v_cnt number;
 v_chr number := 65;
 v_txt clob := 
 '<mapInfo MapType="1~"/>
<mapInfo MapType="1~"/>
<mapInfo MapType="1~"/>
<mapInfo MapType="1~"/>
<mapInfo MapType="1~"/>
<mapInfo MapType="1~"/>
<mapInfo MapType="1~"/>
<mapInfo MapType="1~"/>';
begin
 -- get the # of occurance of "1~". Search entire "1~" string to avoid any unintentional replacement, though unlikely to exist.
 v_cnt := REGEXP_COUNT(v_txt, '"1~"');
 for i in 1..v_cnt
  loop   
   dbms_output.put_line('char is: '||chr(v_chr));
    
   v_txt := REGEXP_REPLACE(v_txt,'"1~"','"1'||chr(v_chr)||'"',1,i); -- i = replace at ith occurence with current chr(v_chr)
   v_chr := v_chr + 1;  
  end loop;
 dbms_output.put_line(v_txt);
end;

My Incorrect Output:

char is: A
char is: B
char is: C
char is: D
char is: E
char is: F
char is: G
char is: H
<mapInfo MapType="1A"/>
<mapInfo MapType="1~"/>
<mapInfo MapType="1B"/>
<mapInfo MapType="1~"/>
<mapInfo MapType="1C"/>
<mapInfo MapType="1~"/>
<mapInfo MapType="1D"/>
<mapInfo MapType="1~"/>

Expected output:

char is: A
char is: B
char is: C
char is: D
char is: E
char is: F
char is: G
char is: H
<mapInfo MapType="1A"/>
<mapInfo MapType="1B"/>
<mapInfo MapType="1C"/>
<mapInfo MapType="1E"/>
<mapInfo MapType="1F"/>
<mapInfo MapType="1G"/>
<mapInfo MapType="1H"/>
<mapInfo MapType="1I"/>
This post has been answered by Paulzip on Aug 23 2022
Jump to Answer
Comments
Post Details
Added on Aug 23 2022
6 comments
161 views