【问题标题】:Oracle: Replace multiple string occurrencesOracle:替换多个字符串出现
【发布时间】:2016-06-14 10:00:38
【问题描述】:

只是快速检查一下,是否可以用单个 select 语句替换所有出现的地方。如果没有,我们计划编写一个函数来执行此替换。

示例字符串

select '#col1:val1@, #col2:val2@, #col3:val3@, #col4:val4@, #col5:val5@' str from dual

预期输出

str
---
col1 val1, col2 val2, col3 val3, col4 val4, col5 val5

到目前为止的代码

with test_table as 
(Select '#col1:val1@, #col2:val2@, #col3:val3@, #col4:val4@, #col5:val5@' str from dual)

   select level "occurrence", REGEXP_substr(str, '#(.*?):', 1, level, 'in', 1) "column", REGEXP_substr(str, ':(.*?)@', 1, level, 'in', 1) "value"
   from test_table
   CONNECT BY REGEXP_COUNT(str, '#.+?:.+?@') >= level

其他详情

  1. 字符串模式是固定的并且事先已知。
  2. 给定模式的出现是动态的,可能有任意数量的 [column:value] 对 - 它们实际上是 [table column:alias] 集。
  3. 为了简单起见,我已经修剪了示例字符串,但是它包含其他详细信息(表连接、where 子句等),因此我们需要替换所有出现的地方。这实际上是一个 select 语句。

【问题讨论】:

    标签: regex string oracle replace


    【解决方案1】:

    查询

    SELECT REGEXP_REPLACE(
             '#col1:val1@, #col2:val2@, #col3:val3@, #col4:val4@, #col5:val5@',
             '#(.*?):(.*?)@',
             '\1 \2'
           ) AS str
    FROM   DUAL
    

    输出

    STR
    -----------------------------------------------------
    col1 val1, col2 val2, col3 val3, col4 val4, col5 val5
    

    【讨论】:

      【解决方案2】:

      我的尝试:

      with test_table as 
      (Select '#col1:val1@, #col2:val2@, #col3:val3@,     #col4:val4@, #col5:val5@' str 
       from dual)
      
      select regexp_replace(regexp_replace(str, '[#@]', ''), '[ :]+', ' ') rez 
      from test_table
      ;
      

      内部 regexp_replace 将 # 和 @ 替换为空字符串(空字符串),外部 regexp 将 : 和空格替换为一个空格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-01
        • 2017-02-26
        • 2017-04-16
        • 2021-02-09
        • 2021-10-31
        • 2015-09-23
        • 2020-07-06
        • 1970-01-01
        相关资源
        最近更新 更多