regexp_like查找10次出现的0

时间:2019-10-25 13:46:57

标签: sql oracle

with smpl as
(
    select '000-000-0000' num from dual union
    select '0000000000' from dual union
    select '00000000000' from dual
)
select * from smpl
where regexp_like(num, '0{10}');

输出:

0000000000
00000000000

如何获取10次出现0(带可选的'-')的记录 预期:

0000000000
000-000-0000

3 个答案:

答案 0 :(得分:2)

使用TRANSLATE去除不需要的字符,然后LENGTH

with smpl as
(
    select '000-000-0000' num from dual union
    select '0000000000' from dual union
    select '000000000' from dual union
    select '00000000000' from dual
)
select * from smpl
where LENGTH( TRANSLATE( num, '0-', '0' ) ) = 10

或与0000000000进行比较:

with smpl as
(
    select '000-000-0000' num from dual union
    select '0000000000' from dual union
    select '000000000' from dual union
    select '00000000000' from dual
)
select * from smpl
where TRANSLATE( num, '0-', '0' ) = '0000000000'

输出

| NUM          |
| :----------- |
| 000-000-0000 |
| 0000000000   |

db <>提琴here

答案 1 :(得分:0)

使用regexp,这是一种简单的方法:

where regexp_count(num, '0') = 10

但是,如果与'0'唯一不同的字符是'-',我希望使用非正则表达式解决方案

答案 2 :(得分:0)

我想指出,您可以使用正则表达式严格执行此操作。如果要在字符串中的任意位置查找模式:

where regexp_like(num, '(\-*0){10}')

如果仅在字符串中查找该模式:

where regexp_like(num, '^(\-*0){10}\-*$')