为什么这个regexp_like无法得到我想要的结果

时间:2018-06-27 16:34:15

标签: sql oracle regexp-like

我正在尝试使用以下regexp_like进行较大的查询,但它不起作用,我在做什么错?

with xx as
  (select '333-22-234223' as a
   from dual)
select xx.a
from xx
where
  regexp_like(xx.a,'^[:digit:]{3}-[:digit:]{2}-[:digit:]{6}$');

3 个答案:

答案 0 :(得分:3)

您可以使用[[:digit:]](双[...])以下解决方案:

WITH xx AS (
    SELECT '333-22-234223' AS a FROM dual
)
SELECT xx.a
FROM xx
WHERE REGEXP_LIKE(xx.a, '^[[:digit:]]{3}-[[:digit:]]{2}\-[[:digit:]]{6}$');

...或使用[0-9]代替[[:digit:]]

WITH xx AS (
    SELECT '333-22-234223' AS a FROM dual
)
SELECT xx.a
FROM xx
WHERE REGEXP_LIKE(xx.a, '^[0-9]{3}-[0-9]{2}\-[0-9]{6}$');
  

演示: http://sqlfiddle.com/#!4/3149e4/120/1


为什么需要双括号?

  

这些字符类仅在带括号的表达式内有效。
  来源: https://docs.oracle.com/cd/B12037_01/server.101/b10759/ap_posix001.htm

答案 1 :(得分:2)

@Sebastion Brosch的替代方法

您可以使用明确的数字范围替换字符类([:digit:]),如下所示:

with xx as
(select '333-22-234223' as a
from dual)
select xx.a
from xx
where
regexp_like(xx.a,'^[0-9]{3}-[0-9]{2}-[0-9]{6}$');

答案 2 :(得分:1)

出于完整性考虑,您也可以将\d用作数字:

with xx as
  (select '333-22-234223' as a
   from dual)
select xx.a
from xx
where regexp_like(xx.a,'^\d{3}-\d{2}-\d{6}$');