Question

Is there any nice trick to change values in string using dictionary mapping? For example I have table1 FIDDLE

+---------------------------+
|          ROW1             |
+---------------------------+
| This is an example string |
| This String has typ0s     |
+---------------------------+

And some mapping table dict1 FIDDLE:

+-------------------------+
|     OLD    |    NEW     |
+-------------------------+
| THIS       | THAT       |
| IS         | ARE        |
| EXAMPLE    | SOURCE     |
| STRING     | NUMBER     |
+------------+------------+

I need some SELECT statement that will split values in table1.row1 and change words using mapping dictionary dict1 so received values will be ( changing no existing dictionary values to upper is optional):

+---------------------------+
|      TRANS_ROW1           |
+---------------------------+
| THAT ARE AN SOURCE NUMBER |
| THAT NUMBER HAS TYP0S     |
+---------------------------+

PS. Spliting using REGEXP expression will be so nice..

Was it helpful?

Solution

WITH dict1 AS
 (SELECT 'THIS' fr,
         'THAT' t
    FROM dual
  UNION ALL
  SELECT 'IS' fr,
         'ARE' t
    FROM dual
  UNION ALL
  SELECT 'EXAMPLE' fr,
         'SOURCE' t
    FROM dual
  UNION ALL
  SELECT 'STRING' fr,
         'NUMBER' t
    FROM dual),
table1 AS
 (SELECT 'This is an example string' AS str,
         1 AS sn
    FROM dual
  UNION ALL
  SELECT 'This String has typ0s' AS str,
         2 sn
    FROM dual),
src AS
 (SELECT regexp_substr(upper(s.str), '[^ ]+', 1, LEVEL) str2,
         s.*,
         rownum nn
    FROM table1 s
  CONNECT BY instr(TRIM(' ' FROM str), ' ', 1, LEVEL - 1) > 0
         AND PRIOR sn = sn
         AND PRIOR dbms_random.value IS NOT NULL),
repl AS
 (SELECT nvl2(dict1.t, dict1.t, src.str2) lex,
         sn,
         nn
    FROM src
    LEFT JOIN dict1
      ON dict1.fr = src.str2)
SELECT listagg(lex, ' ') within GROUP(ORDER BY nn),
       sn
  FROM repl
 GROUP BY sn

It works now as you ask. Enjoy.

EDIT: FIDDLE with solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top