oracle 11g获取正则表达式子匹配

时间:2013-10-22 09:09:41

标签: regex oracle oracle11g

对于我的pl / sql程序,我必须从文本字段中提取子匹配并将这些值插入另一个表...

正则表达式类似于:/^(xyz|abc)(\w{3,3})(\d{0,2})(\d{2,2})(a|ab|ef)$/

所以我想要的是在伪sql中基本上是这样的:

select 
  rtbl.1,  -- should return xyz
  rtbl.2,  -- should return GGG
  rtbl.3,  -- should return 1
  rtbl.4,  -- should return xyz
  rtbl.5   -- should return ef
from regex('xyzGGG122ef', /^(xyz|abc)(\w{3,3})(\d{0,2})(\d{2,2})(a|ab|ef)$/) rtbl;

怎么办呢?

2 个答案:

答案 0 :(得分:1)

您可以使用regexp_substr获取子匹配:

SELECT 
  regexp_substr('xyzGGG122ef', '^(xyz|abc)(\w{3,3})(\d{0,2})(\d{2,2})(a|ab|ef)$', 1, 1, NULL, 1),
  regexp_substr('xyzGGG122ef', '^(xyz|abc)(\w{3,3})(\d{0,2})(\d{2,2})(a|ab|ef)$', 1, 1, NULL, 2),
  regexp_substr('xyzGGG122ef', '^(xyz|abc)(\w{3,3})(\d{0,2})(\d{2,2})(a|ab|ef)$', 1, 1, NULL, 3),
  regexp_substr('xyzGGG122ef', '^(xyz|abc)(\w{3,3})(\d{0,2})(\d{2,2})(a|ab|ef)$', 1, 1, NULL, 4),
  regexp_substr('xyzGGG122ef', '^(xyz|abc)(\w{3,3})(\d{0,2})(\d{2,2})(a|ab|ef)$', 1, 1, NULL, 5)
FROM dual;

您要获取的组是最后一个参数。 在此处阅读更多内容:Oracle Documentation on regexp_substr

答案 1 :(得分:0)

轻微修改以上答案:

SELECT
      ROWNUM,
      POS
FROM
      (SELECT
            REGEXP_SUBSTR (
                         'xyzGGG122ef',
                         '^(xyz|abc)(\w{3,3})(\d{0,2})(\d{2,2})(a|ab|ef)$',
                         1,
                         1,
                         NULL,
                         ROWNUM )
                POS
       FROM
            DUAL
       CONNECT BY
            LEVEL <= 5) RTBL;