oradbanj
oradbanj

Reputation: 563

REGEXP_REPLACE in Oracle

I need to use REGEXP_REPLACE to do the following :

 If word starts with 'ABCD' then replace first four(4) chars with 'FFFF'
    else
 If word starts with 'XYZ' then replace first three(3) chars with 'GGG'

How do I use REGEXP_REPLACE to do conditional replace ?

Upvotes: 1

Views: 442

Answers (2)

Radagast81
Radagast81

Reputation: 3016

If it has to be REGEXP_REPLACE you'll have to combine two function calls:

REGEXP_REPLACE( 
  REGEXP_REPLACE(word,'^ABCD','FFFF')
  ,'^XYZ', 'GGG')

But I would prevere Gordon's caseapproach...

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1270993

You can use case and string operations:

select (case when word like 'ABCD%'
             then 'FFFF' || substr(word, 5)
             when word like 'XYZ%'
             then 'GGG' || substr(word, 4)
             else word
        end) as new_word

Upvotes: 1

Related Questions