使用REGEXP_SUBSTR获取字符串中的特定文本

时间:2013-09-16 03:20:17

标签: sql oracle oracle11g

我有一个字符串,其中存储了大量数据。字符串如下所示:

DUTBOARD|A1DT25522;LOADBOARD|A2LB1896;PROBECARD|A4PC40257;PROGRAMNAME|DS2781;TESTOPTION|POSTBAKE;TESTTEMP|ROOM TEMP

我需要的是只显示Dutboard,Loadboard,Probecard,Cable和Motherboard及其值。我打算使用REGEXP_SUBSTR,然后将它们连接起来。这就是我到目前为止所做的:

SELECT  'DUTBOARD|A1DT25522;LOADBOARD|A2LB1896;PROBECARD|A4PC40257;PROGRAMNAME|DS2781;TESTOPTION|POSTBAKE;TESTTEMP|ROOM TEMP' hw
  , regexp_substr('DUTBOARD|A1DT25522;LOADBOARD|A2LB1896;PROBECARD|A4PC40257;PROGRAMNAME|DS2781;TESTOPTION|POSTBAKE;TESTTEMP|ROOM TEMP', '(;|^)LOADBOARD\|(.*)(;|$)', 1, 1, '', 2) lol
FROM dual

非常感谢。

2 个答案:

答案 0 :(得分:0)

WITH tab AS
     (SELECT     REGEXP_SUBSTR
                    ('DUTBOARD|A1DT25522;LOADBOARD|A2LB1896;PROBECARD|A4PC40257;PROGRAMNAME|DS2781;TESTOPTION|POSTBAKE;TESTTEMP|ROOM TEMP',
                     '[^;]+',
                     1,
                     LEVEL
                    ) regular_expression
            FROM DUAL
      CONNECT BY REGEXP_SUBSTR
                    ('DUTBOARD|A1DT25522;LOADBOARD|A2LB1896;PROBECARD|A4PC40257;PROGRAMNAME|DS2781;TESTOPTION|POSTBAKE;TESTTEMP|ROOM TEMP',
                     '[^;]+',
                     1,
                     LEVEL
                    ) IS NOT NULL)
SELECT REGEXP_SUBSTR (regular_expression, '[^|]+'),
       REGEXP_REPLACE (regular_expression, '.*\|([^ ]*).*', '\1')
  FROM tab

<强>输出

http://www.sqlfiddle.com/#!4/d41d8/17310

答案 1 :(得分:0)

那么您是要提取这些特定字段然后重新连接数据?如果您没有特别依赖REGEX_SUBSTR,这会对您有用吗?

WITH TestStringsCTE AS (
  SELECT REGEXP_REPLACE(str, '.*DUTBOARD\|([^;|]+);.*', '\1') AS DUTBOARD
    ,REGEXP_REPLACE(str, '.*LOADBOARD\|([^;|]+);.*', '\1') AS LOADBOARD
    ,REGEXP_REPLACE(str, '.*PROBECARD\|([^;|]+);.*', '\1') AS PROBECARD
  FROM TestStrings)

SELECT ('DUTBOARD'||'|'||DUTBOARD||';'
        ||'LOADBOARD'||'|'||LOADBOARD||';'
        ||'PROBECARD'||'|'||PROBECARD||';') AS str FROM TestStringsCTE;

http://sqlfiddle.com/#!4/19ee7/15