使用REGEXP_SUBSTR或SUBSTR函数在Oracle SQL中查找子字符串“首先_(下划线)开始”和“第二_(下划线)结束”

时间:2017-03-07 06:45:39

标签: sql oracle substr regexp-substr

我的输入模式如下:

WITH data_tab AS (
  SELECT '1540_INPUTTER' user_name FROM  dual 
  UNION SELECT '1540_RAZZ25_UNKNOWN' FROM  dual
  UNION SELECT '1540_RAKIB17_OS_WIN10' FROM  dual
  )
SELECT REGEXP_SUBSTR(user_name,…………………….....) AS st_user_name from data_tab

期望输出:

ST_USER_NAME
------------
INPUTTER
RAZZ25
RAKIB17

4 个答案:

答案 0 :(得分:1)

一种方法是

WITH data_tab AS (
    SELECT '1540_INPUTTER' user_name FROM  dual 
    UNION SELECT '1540_RAZZ25_UNKNOWN' FROM  dual
    UNION SELECT '1540_RAKIB17_OS_WIN10' FROM  dual
)
SELECT REGEXP_SUBSTR(user_name,'_([^_]*)', 1, 1, 'i', 1) AS st_user_name 
FROM data_tab;

答案 1 :(得分:0)

另一种方法是定义字符串的完整结构 并提取第二组:

WITH data_tab AS (
  SELECT '1540_INPUTTER' user_name FROM  dual
  UNION SELECT '1540_RAZZ25_UNKNOWN' FROM  dual
  UNION SELECT '1540_RAKIB17_OS_WIN10' FROM  dual
  )
SELECT REGEXP_SUBSTR(user_name,'(\d{4}_)([A-Z0-9]+)(_)?(\w+)?',1,1,'i',2)

AS st_user_name     FROM data_tab;

答案 2 :(得分:0)

检查这个。

$ cov-manage-im  --mode defects --show --auth-key-file $auth --host $host --port $port --output fields
            action
            cid
            checker
            classification
            component
            ext-ref
            file
            function
            owner
            severity
            status
            legacy
            stream-name     (stream scope only) 

答案 3 :(得分:-1)

这是一种使用标准字符串操作(没有正则表达式,更耗时)和处理各种特殊情况(参见其他测试数据)的经济方法。

with data_tab as (
       select '1540_INPUTTER'        user_name from dual union all
       select '1540_RAZZ25_UNKNOWN'            from dual union all
       select '1540_RAKIB17_OS_WIN10'          from dual union all
       select 'MATHGUY_'                       from dual union all
       select 'NOUNDERSCORES'                  from dual
     )
select user_name,
       substr(user_name, nullif(instr(user_name, '_'), 0) + 1,
              instr(user_name || '_', '_', 1, 2) - instr(user_name, '_') - 1) 
                                                                      as st_user_name
from   data_tab
;

USER_NAME             ST_USER_NAME
--------------------- ------------
1540_INPUTTER         INPUTTER
1540_RAZZ25_UNKNOWN   RAZZ25
1540_RAKIB17_OS_WIN10 RAKIB17
MATHGUY_
NOUNDERSCORES