由分隔符oracle拆分后的子字符串

dgsult0t  于 2022-11-22  发布在  Oracle
关注(0)|答案(3)|浏览(217)

比如说我有一个字符串“123456,852369,7852159,1596357”输出要查找的字符串“1234,8523,7852,1596”
要求是....我们希望在每个','分隔符后收集4个字符
如拆分、子字符串和concat

select
  REGEXP_REPLACE('MEDA,MEDA,MEDA,MEDA,MEDA,MEDA,MEDA,MEDA,MDCB,MDCB,MDCB,MDCB,MDCB,MDCB', '([^,]+)(,\1)+', '\1')
from dual;
5gfr0r5j

5gfr0r5j1#

我们希望在每个“,”分隔符后收集4个字符
以下是使用regexp_replace的方法:

select regexp_replace(
    '123456,852369,7852159,1596357',
    '([^,]{4})[^,]*(,|$)',
    '\1\2'
)
from dual

正则表达式分解:

([^,]{4})    4 characters others than "," (capture that group as \1)
[^,]*        0 to n characters other than "," (no capture)
(,|$)        either character "," or the end of string (capture this as \2)

该函数用capture 1(我们需要的4个字符)和capture 2(分隔符,如果有的话)替换每个匹配。

Demo

| 结果|
| - -|
| 1234,8523,7852,1596个单位|

wbrvyc0a

wbrvyc0a2#

一个选项可能是拆分字符串,提取4个字符并将其聚合回来:

SQL> with test (col) as
  2    (select '123456,852369,7852159,1596357' from dual)
  3  select listagg(regexp_substr(col, '[^,]{4}', 1, level), ',')
  4         within group (order by level) result
  5  from test
  6  connect by level <= regexp_count(col, ',') + 1;

RESULT
--------------------------------------------------------------------------------
1234,8523,7852,1596

SQL>
qq24tv8q

qq24tv8q3#

使用REGEX_REPLACE

select regexp_replace(the_string, '(^|,)([^,]{4})[^,]*', '\1\2')
from mytable;

这看起来
1.字符串的开头或逗号
1.然后是四个不是逗号的字符
1.然后是任意数量的非逗号结尾字符
只保留了
1.开头或逗号
1.后面的四个字符
演示:https://dbfiddle.uk/efUFvKyO

相关问题