在Oracle中用符号替换单词

wlwcrazw  于 2023-04-11  发布在  Oracle
关注(0)|答案(2)|浏览(171)

我需要用替换一个单词,但我需要在世界的长度之前计数,因为我只需要隐藏单词的一半

question -> ques••••
World -> wor••

有什么想法吗?
regex_replace函数能解决这个问题吗?
我尽力了

SELECT REGEXP_REPLACE(REGEXP_REPLACE('Stack Overflow','(\w)\w','\1*'), '\*\w', '**') 
FROM DUAL;

这就是结果

S•••• O•••••••

我想要的结果是:

Sta•• Over••••
bjg7j2ky

bjg7j2ky1#

看看这个选项是否有帮助。
示例字符串:

SQL> with test (col) as
  2    (select 'Stack Overflow' from dual),

将其拆分为单词(以空格字符分隔):

3  temp as
  4    -- word-by-word
  5    (select        regexp_substr(col, '[^ ]+', 1, level) word,
  6            length(regexp_substr(col, '[^ ]+', 1, level)) len,
  7            level lvl
  8     from test
  9     connect by level <= regexp_count(col, ' ') + 1
 10    )

屏蔽每个单词的最后一部分并将结果聚合回来:

11  select listagg(substr(word, 1, trunc(len/2)) || lpad('*', len - trunc(len/2), '*'), ' ')
 12    within group (order by lvl) result
 13  from temp;

RESULT
----------------------------------------
St*** Over****

SQL>
0tdrvxhp

0tdrvxhp2#

如果您希望保留原始单词之间的原始分隔符:(你也可以使用trunc()代替round()来计算分割长度,但是1个字符的字会丢失)

with data(id, s) as (
    select 1, '2 questions' from dual union all
    select 2, 'A World    of ... questions' from dual union all
    select 3, 'Stack, Overflow' from dual
)
select id, 
    listagg( rpad( substr(target,1,round(length(target)/2)),length(target),'*') || sep ,'') within group(order by lvl) as result
from (
    select id, level as lvl, 
        regexp_substr(s,'[^[:punct:][:space:]]+',1,level) as target,
        regexp_substr(s,'[[:punct:][:space:]]+',1,level) as sep
    from data
    connect by level <= regexp_count(s,'[[:punct:][:space:]]+') + 1
        and prior id = id
        and prior sys_guid() is not null
)
group by id
;

1   2 quest****
2   A Wor**    o* ... quest****
3   Sta**, Over****

相关问题