首页 > 解决方案 > 使用带有多个条件的 REGEXP_LIKE 来匹配模式

问题描述

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

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

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

with test 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  '2614-210297-103-6' ID from dual
)        
select
case
    when regexp_like(ID, '^\d{4}-\d{6}-\d{3}-\d{1}$') 
        then ID
    else
        case
            when regexp_count(ID, '\d') = 14
                then
                    case
                        when
                            not regexp_like(ID,'^15|^2-8|^00|^000|^0000')
                        then ID
                    end
            else ID
        end
end ID_tr
from test

标签: sqlregexoracle

解决方案


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

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                    

推荐阅读