Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Avik.

Asked: June 07, 2017 - 7:59 pm UTC

Last updated: June 09, 2017 - 2:15 am UTC

Version: Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production

Viewed 1000+ times

You Asked

Hi Tom,

Here's something I observed and couldn't make anything out of it.

Considering the below two queries: (To summarize, I took a string of 9 repeating characters, and replacing the nth character (3rd in the example) with another character. Ideally replacing a character with another shouldn't alter the length of the original string)

SELECT LENGTH(REGEXP_REPLACE('*********', '*', 'X', 3, 1))  FROM DUAL;


The above query somehow "increases" the length of the original string from 9 to 10, while the below query (essentially the same, just using '-' instead of '*')

SELECT LENGTH(REGEXP_REPLACE('---------', '-', 'X', 3, 1))  FROM DUAL;


"maintains" the length of the original string.

I've tested with multiple other characters, but this discrepancy is happening only with '*'.

Can you help me understand this?



with LiveSQL Test Case:

and Connor said...

"*" is a special character in REGEX, so you are not *really* replacing the asterisk. To reference a special character (asterisk being an example) you need to escape it.

SQL> SELECT LENGTH(REGEXP_REPLACE('*********', '*', 'X', 3, 1))  FROM DUAL;

SQL> SELECT LENGTH(REGEXP_REPLACE('*********', '\*', 'X', 3, 1))  FROM DUAL;
                                               9


You can see the list of special characters/expressions here

https://docs.oracle.com/database/122/SQLRF/Oracle-Regular-Expression-Support.htm#SQLRF020

Rating

  (1 rating)

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

Comments

Thank you !!

Avik, June 08, 2017 - 3:17 am UTC

Thank you Connor !!

That was supposed to be somewhat obvious, but didn't struck me at all. I wasn't aware that asterisk is a special character (all these years I was quite occupied with escaping single quotes and %-s.... Although we use SELECT * all the time.. My bad !).

Thanks again !
Connor McDonald
June 09, 2017 - 2:15 am UTC

No problem. We all ask questions that stump us only to have that awkward moment when someone points out an obvious solution.

Generally I just lie and say "Yeah *I* knew...I was asking for somebody else"

:-)