String replacement based on condition in Oracle

259 views Asked by At


I was working with some requirement where I need to display some data based on some certain condition.
Below is the values I am giving here as a examples.
The conditions are like If first 4 characters of the column is NUMERIC then it will further check if it has SPACE otherwise gives the right hand side part after 4 characters.
If it will look for SPACE then it will look further if the right side from the SPACE has any DOT, if yes then gives the right side part of the DOT.

Column1         Column_new   
-----------     ----------         
22 50.IND1 E    IND1 E
RYST 22S2E      22S2E
2608.S1 E       S1 E
0540BS2         BS2

Here is the code I was trying but still need some modification as i am confused of multiple conditions in same case statement

SELECT COLUMN1,
  CASE
    WHEN LENGTH(TRIM(TRANSLATE(SUBSTR(t1.COLUMN1,0,4), '0123456789',' '))) IS NULL
    THEN (
      CASE
        WHEN instr(t1.COLUMN1,'.')>0
        THEN SUBSTR(t1.COLUMN1,instr(t1.COLUMN1,'.')+1,LENGTH(t1.COLUMN1))
        ELSE t1.COLUMN1
      END)
    WHEN instr(t1.COLUMN1,' ')>0
    THEN trim(SUBSTR(t1.COLUMN1,instr(t1.COLUMN1,' ')+1,LENGTH(t1.COLUMN1)))
      --     when instr(t1.COLUMN1,'.')>0
      --        then (case when instr(trim(substr(t1.COLUMN1,instr(t1.COLUMN1,' '),length(t1.COLUMN1))),'.')>0 then substr(trim(substr(t1.COLUMN1,instr(t1.COLUMN1,' '),length(t1.COLUMN1))),
    ELSE t1.COLUMN1
  END AS COLUMN_NEW
FROM TABLE t1
WHERE ...
AND ...
AND ... ;
1

There are 1 answers

2
Radagast81 On BEST ANSWER

Typically you use a regular expression for these kind of problems. The following might be what you are looking for:

SELECT COLUMN1, REGEXP_REPLACE(COLUMN1,'^([0-9 ]{4}|.* )(.*\.)?','') COLUMN_NEW 
  FROM TABLE t1