将REGEXP_LIKE与多重条件配合使用以匹配模式

时间:2019-07-08 07:04:21

标签: sql regex oracle

表名:test Column_Name:ID 列ID的正确格式-'^ \ d {4}-\ d {6}-\ d {3}-\ d1} $'

条件: 必须与上述格式匹配,但不能以15开头,数字从2-8,00,000和0000。

使用REGEXP_LIKE匹配指定的条件,但无法在单个REGEXP_LIKE中包括场景开始:

{{1}}

2 个答案:

答案 0 :(得分:0)

这可能是一种简化条件的方法,即使不是在一个正则表达式中也是如此:

regexp_like(ID, '^[190]\d{3}-\d{6}-\d{3}-\d$') and
substr(ID, 1, 2) not in ('00', '15')

在这里,我仅使用^[190]\d{3}而不是^\d{4}进行匹配,前提是第一位数字不在2-8之间。 我发现避免使用以15或00、000、0000开头的字符串的唯一方法是使用substr检查前两个字符。

使用您的数据,

select ID,
    case
     when regexp_like(ID, '^[190]\d{3}-\d{6}-\d{3}-\d$') and
          substr(ID, 1, 2) not in ('00', '15') then ID
    end as result
from test

给予:

ID                 RESULT            
------------------ ------------------
0614-210297-103-6  0614-210297-103-6 
0014-210297-103-6                    
0004-210297-103-6                    
0000-210297-103-6                    
00120792-2..                         
0614- 210297-103-6                   
0614210297-103-6                     
2614-210297-103-6                    

答案 1 :(得分:0)

您说“不得以15开头,数字应为2-8、00、000、0000”。

您可以简化为:不得以00、15、2n到8n开头。

或者您可以肯定而不是否定:必须以01到09、10到14或16到19或9n开头。

在积极的条件下,您可以获得一个REGEXP:

with test(id) as (
select  '0614-210297-103-6' ID from dual union all
select  '0014-210297-103-6' ID from dual union all
select  '0004-210297-103-6' ID from dual union all
select  '0000-210297-103-6' ID from dual union all
select  '00120792-2..' ID from dual union all
select  '0614- 210297-103-6' ID from dual union all
select  '0614210297-103-6' ID from dual union all
select  '1514-210297-103-6' ID from dual union all
select  '1614-210297-103-6' ID from dual union all
select  '2614-210297-103-6' ID from dual union all
select  '9614-210297-103-6' ID from dual
)      
select id from test
where regexp_like(id,'^(0[1-9]|1[1-46-9]|9\d)\d{2}-\d{6}-\d{3}-\d$')

ID
0614-210297-103-6
1614-210297-103-6
9614-210297-103-6