如何在Oracle中使用Regexp_Replace替换字符串

时间:2019-03-13 10:36:45

标签: oracle oracle11g oracle10g

我要替换这个:

Swig::Director *

与此:

"STORES/KOL#10/8/36#1718.00#4165570.00#119539388#PT3624496#9902001#04266#6721#PT3624496-11608091-1-55-STORES/KOL"

基本上这是基于条件的替换,我想将"STORES/KOL#10#8#36#1718.00#4165570.00#119539388#PT3624496#9902001#04266#6721#PT3624496-11608091-1-55-STORES/KOL" 替换为/#这样的字符串应为STORES/KOLSTORES/KOL字符串应为10/8/36

3 个答案:

答案 0 :(得分:0)

这是使用REGEXP_REPLACE的一个选项。我们可以尝试定位以下正则表达式模式:

#(\d+)/(\d+)/(\d+)#

然后使用三个捕获组进行替换,将路径分隔符替换为井号。

WITH yourTable AS (
    SELECT 'STORES/KOL#10/8/36#1718.00#4165570.00#119539388#PT3624496#9902001#04266#6721#PT3624496-11608091-1-55-STORES/KOL' AS input FROM dual
)

SELECT
    input,
    REGEXP_REPLACE(input, '#(\d+)/(\d+)/(\d+)#', '#\1#\2#\3#') AS output
FROM yourTable;

Demo

此正则表达式替换是否足够具体/准确,您的其余数据取决于该数据,而您从未向我们显示过。

答案 1 :(得分:0)

这将用/替换第二个和第三个#字符:

Oracle设置

CREATE TABLE test_data ( value ) AS
SELECT '"STORES/KOL#10/8/36#1718.00#4165570.00#119539388#PT3624496#9902001#04266#6721#PT3624496-11608091-1-55-STORES/KOL"'
FROM   DUAL;

查询

SELECT REGEXP_REPLACE(
         value,
         '^(.*?/.*?)/(.*?)/(.*)$',
         '\1#\2#\3'
       ) AS replacement
FROM   test_data

输出

| REPLACEMENT                                                                                                       |
| :---------------------------------------------------------------------------------------------------------------- |
| "STORES/KOL#10#8#36#1718.00#4165570.00#119539388#PT3624496#9902001#04266#6721#PT3624496-11608091-1-55-STORES/KOL" |

db <>提琴here

答案 2 :(得分:0)

with s as (select '"STORES/KOL#10/8/36#1718.00#4165570.00#119539388#PT3624496#9902001#04266#6721#PT3624496-11608091-1-55-STORES/KOL"' str from dual)
select 
replace(replace(str, '/', '#'), 'STORES#KOL', 'STORES/KOL') result_str_1,
regexp_replace(str, '(\d)/', '\1#')                         result_str_2
from s;