如何从字符串中提取子字符串?

时间:2017-04-18 12:43:19

标签: sql oracle

fnd YGY LOOKUP_TYPE = 'welcome' HELO HIASDH LOOKUP_TYPE = 'home' hello how are you?

上面是字符串,我希望输出为

welcome
home

2 个答案:

答案 0 :(得分:3)

查询1

注意:单引号需要在文字文字中进行转义

WITH test_data ( string ) AS (
  SELECT 'LOOKUP_TYPE = ''welcome'' LOOKUP_TYPE = ''home'''
  FROM DUAL
)
SELECT SUBSTR( string, quote1 + 1, quote2 - quote1 - 1 ) AS first_quoted_string,
       SUBSTR( string, quote3 + 1, quote4 - quote3 - 1 ) AS second_quoted_string,
FROM   (
  SELECT string,
         INSTR( string, '''', 1, 1 ) AS quote1,
         INSTR( string, '''', 1, 2 ) AS quote2,
         INSTR( string, '''', 1, 3 ) AS quote3,
         INSTR( string, '''', 1, 4 ) AS quote4
  FROM   test_data
)

<强>输出

FIRST_QUOTED_STRING SECOND_QUOTED_STRING
------------------- --------------------
welcome             home

查询2

注意:使用了替代text literal引用解析器q'[your string]',因此单引号不需要转义

WITH test_data ( string ) AS (
  SELECT q'[LOOKUP_TYPE = 'welcome' LOOKUP_TYPE = 'home']'
  FROM DUAL
),
quotes ( string, quote_start, quote_end, lvl ) AS (
  SELECT string,
         INSTR( string, '''', 1, 1 ),
         INSTR( string, '''', 1, 2 ),
         1
  FROM   test_data
  WHERE  INSTR( string, '''', 1, 2 ) > 0
UNION ALL
  SELECT string,
         INSTR( string, '''', 1, 2 * lvl + 1 ),
         INSTR( string, '''', 1, 2 * lvl + 2 ),
         lvl + 1
  FROM   quotes
  WHERE  INSTR( string, '''', 1, 2 * lvl + 2 ) > 0
)
SELECT SUBSTR( string, quote_start + 1, quote_end - quote_start - 1 ) AS quoted_string
FROM   quotes

<强>输出

QUOTED_STRING
-------------
welcome
home

查询3 - 正则表达式

注意::your_string绑定变量用于获取输入(您也可以使用文本文字)

WITH test_data ( string ) AS (
  SELECT :your_string FROM DUAL
),
quotes ( string, quoted_string, lvl, max_lvl ) AS (
  SELECT string,
         REGEXP_SUBSTR( string, q'[LOOKUP_TYPE\s*=\s*("|''?)(.*?)\1]', 1, 1, NULL, 2 ),
         1,
         REGEXP_COUNT( string, q'[LOOKUP_TYPE\s*=\s*("|''?)(.*?)\1]' )
  FROM   test_data
  WHERE  REGEXP_COUNT( string, q'[LOOKUP_TYPE\s*=\s*("|''?)(.*?)\1]' ) > 0
UNION ALL
  SELECT string,
         REGEXP_SUBSTR( string, q'[LOOKUP_TYPE\s*=\s*("|''?)(.*?)\1]', 1, lvl + 1, NULL, 2 ),
         lvl + 1,
         max_lvl
  FROM   quotes
  WHERE  lvl < max_lvl
)
SELECT quoted_string
FROM   quotes

<强>输出

QUOTED_STRING
-------------
welcome
home

答案 1 :(得分:1)

with    t (col) as (select q'[fnd YGY LOOKUP_TYPE = 'welcome' HELO HIASDH LOOKUP_TYPE = "home" hello LOOKUP_TYPE = ''man'' how are you?]' from dual)

select  rtrim(regexp_replace(col,q'[(.*?LOOKUP_TYPE\s*=\s*(''|'|")(.*?)\2|.+)]','\3,'),',') as lookup_types
from    t
+------------------+
|   LOOKUP_TYPES   |
+------------------+
| welcome,home,man |
+------------------+