Extract certain pattern with Oracle SQL

余生颓废 提交于 2019-12-06 13:15:32

问题


I have a string like

with xx as (
select 'id9' idno,'untest X456789,W357987 and Q321089 cont group' test from dual)
select * from xx

There are some thosand rows like the following

       IDNO |                             TEST
      +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        id9 | untest X456789,W357987 and Q321089 cont group

I want to extract words that begin with a letter followed by 6 digits. Also, there should be a comma between them (because later I will place them to multiple rows)

Resulting Table:

        IDNO |                TEST
      +++++++++++++++++++++++++++++++++++++++++
        id9 | X456789,X321678,W357987,Q321089

I have tried regexp_replace, but could not reach a solution.

select idno, REGEXP_replace( test,'([^[A-Z]{1}[:digit:]{6},?])') AS test from xx

回答1:


The following does what you want for your original string:

with xx as (
select 'id9' idno,'untest X456789,W357987 and Q321089 cont group' test from dual
)
select idno,
       REGEXP_replace(test,
                      '([A-Z]{1}[0-9]{6}[ ,]?)|(.)', '\1'
                     ) AS test
from xx;

Getting the second space to be a comma . . . you can use a regular replace:

with xx as (
select 'id9' idno,'untest X456789,W357987 and Q321089 cont group' test from dual
)
select idno,
       replace(REGEXP_replace(test,
                              '([A-Z]{1}[0-9]{6}[ ,]?)|(.)', '\1'
                             ),
               ' ', ',') AS test
from xx;

The SQL Fiddle is here.



来源:https://stackoverflow.com/questions/18016412/extract-certain-pattern-with-oracle-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!