PL / SQL,正则表达式,

时间:2016-06-21 10:54:53

标签: regex oracle plsql

2个代码示例:

      WITH A AS
  (SELECT 'this is a test:12/01/2015  01/05/2018'
    || chr(13)
    ||chr(10)
    || ' this is the 2nd line: 07/07/2017' Description
  FROM dual
  )
SELECT to_date(regexp_substr(A.Description , '\d{1,2}/\d{1,2}/\d{4}',1,level),'MM/DD/YYYY')
FROM A
  CONNECT BY level  <= regexp_count(a.description, '\d{1,2}/\d{1,2}/\d{4}');
/

和另一个:

SELECT DISTINCT REGEXP_SUBSTR ('23,34,45,56','[^,]+',1,LEVEL) as "token"
FROM   DUAL
CONNECT BY REGEXP_SUBSTR ('23,34,45,56','[^,]+',1,LEVEL) IS NOT NULL
order by 1;

有人可以解释一下,为什么在第一种情况下我们会使用&#39;&lt; =&#39;而在第二天我们不是吗?

2 个答案:

答案 0 :(得分:0)

Introduced in Oracle 10g 

REGEXP_SUBSTR - 返回与正则表达式匹配的字符串。

Introduced in Oracle 11g 

REGEXP_COUNT - 返回字符串中正则表达式的出现次数。

您可以通过不使用关系运算符&#39;&lt; =&#39; 。 在上面的代码中,您正在计算事件。

WITH A AS
      (SELECT 'this is a test:12/01/2015  01/05/2018'
        || chr(13)
        ||chr(10)
        || ' this is the 2nd line: 07/07/2017' Description
      FROM dual
      )
    SELECT to_date(regexp_substr(A.Description , '\d{1,2}/\d{1,2}/\d{4}',1,level),'MM/DD/YYYY')
    FROM A
      CONNECT BY   
      regexp_substr(A.Description , '\d{1,2}/\d{1,2}/\d{4}',1,LEVEL) is not null;

在第二个查询中,您可以使用&#39;&lt; =&#39;根据需要。

SELECT DISTINCT REGEXP_SUBSTR ('23,34,45,56','[^,]+',1,LEVEL) as "token",LEVEL
        FROM   DUAL
    CONNECT BY LEVEL  <= regexp_count(('23,34,45,56'),'[^,]+');

答案 1 :(得分:0)

有时在IS NOT NULL的输出上使用REGEXP_SUBSTR找到的行数与来自REGEXP_COUNT的行数相同,然后它们执行相同的操作,这是一个问题个人偏好:

SELECT REGEXP_SUBSTR( '1,2,3', '\d+', 1, LEVEL ) AS value
FROM   DUAL
CONNECT BY LEVEL <= REGEXP_COUNT( '1,2,3', '\d+' )

SELECT REGEXP_SUBSTR( '1,2,3', '\d+', 1, LEVEL ) AS value
FROM   DUAL
CONNECT BY REGEXP_SUBSTR( '1,2,3', '\d+', 1, LEVEL ) IS NOT NULL

两个输出:

VALUE
-----
1
2
3

但是,有时匹配的子字符串可以是零宽度(相当于NULL),然后它们不会:

SELECT REGEXP_SUBSTR( '1,2,,4', '(\d*)(,|$)', 1, LEVEL, 1 ) AS value
FROM   DUAL
CONNECT BY LEVEL <= REGEXP_COUNT( '1,2,3', '(\d*)(,|$)' )

输出:

VALUE
------
1
2
(null)
4
(null)

SELECT REGEXP_SUBSTR( '1,2,,4', '(\d*)(,|$)', 1, LEVEL, NULL, 1 ) AS value
FROM   DUAL
CONNECT BY REGEXP_SUBSTR( '1,2,,4', '(\d*)(,|$)', 1, LEVEL, NULL, 1 ) IS NOT NULL

输出:

VALUE
------
1
2

并停在第一个NULL值。

要获得所有结果,您需要使用REGEXP_COUNTREGEXP_SUBSTR()子句中没有NULL函数返回CONNECT BY值(因此,在此示例中,我们可以通过提取完整匹配而不仅仅是捕获组来修复它;即REGEXP_SUBSTR( '1,2,,4', '(\d*)(,|$)', 1, LEVEL ) IS NOT NULL)。