Oracle-用逗号分割字符串,并获取最后一个子字符串

时间:2019-06-10 15:17:22

标签: regex oracle11g

我想编写一个Oracle查询来仅提取逗号分隔的字符串的最后一个子字符串,如下所示:

DEST = "1,MMA SALAI,ARIANKUPAM,CITY CENTRE,G12 47H"

我只对G12感兴趣。如何获得Oracle查询?

谢谢

2 个答案:

答案 0 :(得分:1)

尝试

REGEXP_SUBSTR('1,MMA SALAI,ARIANKUPAM,CITY CENTRE,G12 47H', '[^,]+$')

但这将获取G12 47H。您可能会考虑

REGEXP_SUBSTR('1,MMA SALAI,ARIANKUPAM,CITY CENTRE,G12 47H', '([^, ]+)( +[^,]*)?$', 1,1,NULL,1)

这将得到G12

答案 1 :(得分:1)

一些 substringing (请参见代码中的注释):

SQL> with test (dest) as
  2    (select '1,MMA SALAI,ARIANKUPAM,CITY CENTRE,G12 47H' from dual)
  3  select
  4    regexp_substr(dest,              --> out of the DEST, give me ...
  5                  '\w+',             --> ... the first word that begins right after ...
  6                  instr(dest, ',', 1, regexp_count(dest, ',')) + 1     --> ... postition of the last
  7                 ) result                                              --> comma in the source string
  8  from test;

RESULT
--------------------
G12

SQL>

或者,通过将逗号分隔的值分成几行:

SQL> with test (dest) as
  2    (select '1,MMA SALAI,ARIANKUPAM,CITY CENTRE,G12 47H' from dual)
  3  select regexp_substr(col, '\w+') result
  4  from (select regexp_substr(dest, '[^,]+', 1, level) col,  --> split column to rows
  5               row_number() over (order by level desc) rn   --> the last row will be RN = 1
  6        from test
  7        connect by level <= regexp_count(dest, ',') + 1
  8       )
  9  where rn = 1;

RESULT
--------------------
G12

SQL>
相关问题