简体   繁体   中英

Regarding Oracle Regexp_Replace

I've a string like "Vinoth^Vinoth Karthick Vinoth^Vinoth^Vinoth" delimited by "^". I would like to replace only Vinoth by XXX.

I/P String : Vinoth^Vinoth Karthick Vinoth^Vinoth^Vinoth
Expected output : XXX^Vinoth Karthick Vinoth^XXX^XXX

Please suggest how to do this using Regexp_replace or any other function in ORACLE SQL Statement.

Double up the delimiter ^ characters and wrap the string in delimiter ^ characters so that each element has its own distinct leading and trailing delimiter then you can just replace ^Vinoth^ with ^XXX^ and reverse the doubling of the delimiters and trim the leading and trailing delimiters:

SQL Fiddle

Oracle 11g R2 Schema Setup :

SELECT 1 FROM DUAL;

Query 1 :

SELECT TRIM(
         '^' FROM
         REPLACE(
           REPLACE(
             '^' ||
             REPLACE(
               'Vinoth^Vinoth Karthick Vinoth^Vinoth^Vinoth',
               '^',
               '^^'
             )
             || '^',
             '^Vinoth^',
             '^XXX^'
           ),
           '^^',
           '^'
         )
       ) AS replaced
FROM   DUAL

Results :

|                           REPLACED |
|------------------------------------|
| XXX^Vinoth Karthick Vinoth^XXX^XXX |

Yet another option:

SQL> with test (col) as
  2    (select 'Vinoth^Vinoth Karthick Vinoth^Vinoth^Vinoth' from dual),
  3  inter as
  4    (select regexp_substr(replace(col, '^', ':'), '[^:]+', 1, level) col,
  5            level lvl
  6     from test
  7     connect by level <= regexp_count(col, '\^') + 1
  8    )
  9  select listagg(regexp_replace(col, '^Vinoth$', 'XXX'), '^')
 10    within group (order by lvl) result
 11  from inter;

RESULT
-----------------------------------------------------------------------------

XXX^Vinoth Karthick Vinoth^XXX^XXX

SQL>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM