Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, santhosh.

Asked: February 24, 2017 - 10:50 am UTC

Last updated: February 28, 2017 - 1:33 am UTC

Version: 11g

Viewed 1000+ times

You Asked

hi team ,


i have a scenario.I have a statement a,b,c, here by using regular expression regexp_replace i need to replace the commas in the statement with ||','|| and the last comma in the statement which is present should be replaced with null.

statement = a,b,c,

The output which i need is a||','||b||','||c

i tried the above statement it works can i write in a better way to in order to reduce the code

my code : select regexp_replace(regexp_replace('a,b,c,','[,]$',''),',','||'',''||');​

optimised code?



and Connor said...

SQL> variable str varchar2(30)
SQL> exec :str := 'a,b,c,';

PL/SQL procedure successfully completed.

SQL>
SQL> select
  2    replace(rtrim(:str,','),',',q'{||','||}')
  3  from dual;

REPLACE(RTRIM(:STR,','),',',Q'{||','||}')
---------------------------------------------------------
a||','||b||','||c

1 row selected.


Rating

  (2 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Thank you team

santhosh, February 27, 2017 - 4:41 am UTC

Can i get the little explanation on that query if its possible
thank you

Connor McDonald
February 28, 2017 - 1:29 am UTC

replace(source,X,Y)

will change all occurrences of "X" with "Y"

so in this case:

X = ','
Y = q'{||','||}'

ie, commas becomes ||','||

Because we do *not* want a suffix, we removed the trailing comma in the source string by using rtrim

Break it down

paul, February 27, 2017 - 9:28 pm UTC

If I read it right and google a bit....
rtrim('a,b,c,',',') says remove from the right end of 'char' all of the characters that appear in 'set'.
in this case : char is your 'a,b,c' and set is your ,.

Then do a replace on the result of the rtrim, replacing ',' with '||' using the Text Literal notation to distinguish the "'" as relevant. That is the 'q' that you see.


rtrim: http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions141.htm
replace: http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions134.htm
Text Literal: http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements003.htm#SQLRF00218

Connor McDonald
February 28, 2017 - 1:33 am UTC

Thanks for contributing

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library