简体   繁体   中英

Oracle Update with Regular Expression

I have some values in a column like:

"This is test $ABC variables."

I want to update all the variable definition to below one:

"This is test $ABC$ variables."

How can I write this update statement? Somehow, I couldn't manage.

Do you just want replace() ?

update t
    set col = replace(col, '$ABC', '$ABC$')
     where col like '%$ABC%';

Unfortunately, I'm not good at regular expressions so this poor attempt of mine could probably be replaced by something smarter. Looking forward to see it!

SQL> with test as
  2    (select 'This is test $ABC variables' col from dual union
  3     select 'Stackoverflow says $DEF is so cool' from dual
  4    )
  5  select
  6    col,
  7    regexp_replace(col, '\$\w+',  regexp_substr(col, '\$\w+') || '$') result
  8  from test;

COL                                RESULT
---------------------------------- ----------------------------------------
Stackoverflow says $DEF is so cool Stackoverflow says $DEF$ is so cool
This is test $ABC variables        This is test $ABC$ variables

SQL>

You may use this REGEXP query. The parentheses in '\\$(\\w+)' capture the word following $ in \\1

SELECT REGEXP_REPLACE (
          'This is test $ABC variables.This is a second variable $variable2.I have 100$',
          '\$(\w+)',
          '$\1$')
  FROM DUAL;

O/p:

This is test $ABC$ variables.This is a second variable $variable2$.I have 100$

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