Search code examples
sqlregexoracle-databaseregexp-substr

How to trim the text in different columns in Oracle


I have a string from database field which contains the data in below format. The UW:,Loading:, CBE: fields can be present.

ex1:

"[UW:Loading25,CBE]
[Loading: 100;120;130]
[CBE:150;170;190]"

ex2:

"[UW: CBE]
[CBE: 100;122;130]"

ex3:

"[UW:Loading25]
[Loading: 100;120;130]"

I have to separate them in different columns as mentioned below:

     UW       |    Loading     |  CBE  
--------------|----------------|------------
Loading25,CBE |  100;120;130   | 150;170;190
--------------|----------------|------------
CBE           |                |100;122;130 
--------------|----------------|------------
Loading25     |  100;120;130   |            

How can I resolve this?


Solution

  • You can use regexp_substr together with ltrim for each search patterns :

    with t(str) as
    (
     select '[UW:Loading25,CBE][Loading: 100;120;130][CBE:150;170;190]' from dual union all
     select '[UW: CBE][CBE: 100;122;130]' from dual union all
     select '[UW:Loading25][Loading: 100;120;130]' from dual  
    )
    select ltrim(regexp_substr(str,'UW:([^]]+)'),'UW:') as uw,
           ltrim(regexp_substr(str,'Loading:([^]]+)'),'Loading:') as loading,
           ltrim(regexp_substr(str,'CBE:([^]]+)'),'CBE:') as cbe
      from t;
    
    UW               LOADING        CBE
    -------------    -------------  ------------
    Loading25,CBE    100;120;130    150;170;190
    CBE                             100;122;130
    Loading25        100;120;130    
    

    Repeating words such as Loading or CBE should be noticed during the match of patterns.