首页 > 代码库 > Oracle正则表达式函数:regexp_like、regexp_substr、regexp_instr、regexp_replace

Oracle正则表达式函数:regexp_like、regexp_substr、regexp_instr、regexp_replace

Oracle使用正则表达式4个主要函数:

1、regexp_like 只能用于条件表达式,和 like 类似,但是使用的正则表达式进行匹配,语法很简单:

regexp_like_condition

2、regexp_substr 函数,和 substr 类似,用于拾取合符正则表达式描述的字符子串,语法如下:

regexp_substr

3、regexp_instr 函数,和 instr 类似,用于标定符合正则表达式的字符子串的开始位置,语法如下:

regexp_instr

4、regexp_replace 函数,和 replace 类似,用于替换符合正则表达式的字符串,语法如下:

regexp_replace

这里解析一下几个参数的含义:

1、source_char,输入的字符串,可以是列名或者字符串常量、变量。

2、pattern,正则表达式。

3、match_parameter,匹配选项。

取值范围: i:大小写不敏感; c:大小写敏感;n:点号 . 不匹配换行符号;m:多行模式;x:扩展模式,忽略正则表达式中的空白字符。

4、position,标识从第几个字符开始正则表达式匹配。

5、occurrence,标识第几个匹配组。

6、replace_string,替换的字符串。

 

示例如下:

--创建表及测试数据create table tmp aswith data as (select like as id ,a9999 as str from dual union allselect like       ,a9c          from dual union allselect like       ,A7007        from dual union allselect like       ,123a34cc     from dual union allselect substr     ,123,234,345  from  dual union allselect substr     ,12,34.56:78  from dual union allselect substr     ,123456789    from dual union allselect instr      ,192.168.0.1  from dual union allselect replace    ,(020)12345678 from dual union allselect replace    ,001517729C28 from dual)select * from data ;SELECT * FROM tmp;

--查询结果如下

 

--regexp_like示例SELECT str from tmp where id=like and regexp_like(str,A\d+,i); -- ‘i‘ 忽略大小写

select str from tmp where id=like and regexp_like(str, a\d+);

select str from tmp where id=like and regexp_like(str,^a\d+);

SELECT str from tmp where id=like and regexp_like(str,^a\d+$);

--regexp_substr示例1SELECTstr,regexp_substr(str,[^,]+)     str_1_1,regexp_substr(str,[^,]+,1,1) str_1_1,regexp_substr(str,[^,]+,1,2) str_1_2,  -- occurrence 第几个匹配组regexp_substr(str,[^,]+,2,1) str_2_1   -- position 从第几个字符开始匹配from tmpwhere id=substr;

--regexp_substr示例2SELECTSTR,REGEXP_SUBSTR(STR, \d) STR,REGEXP_SUBSTR(STR, \d+, 1, 1) STR,REGEXP_SUBSTR(STR, \d{2}, 1, 2) STR,REGEXP_SUBSTR(STR, \d{3}, 2, 1) STRFROM TMPWHERE ID = substr;

--regexp_instr示例1SELECTSTR,REGEXP_INSTR(STR, \.) IND,REGEXP_INSTR(STR, \., 1, 2) IND,REGEXP_INSTR(STR, \., 5, 2) INDFROM TMPWHERE ID = instr;

--regexp_instr示例2SELECTregexp_instr(192.168.0.1,\.,1,level) ind ,  -- 点号. 所在的位置regexp_instr(192.168.0.1,\d,1,level) ind    -- 每个数字的位置from dualconnect by level <=  9

--regexp_replace示例SELECT STR,REGEXP_REPLACE(STR, 020, GZ) STR,REGEXP_REPLACE(STR, (\d{3})(\d{3}), <\2\1>) STR -- 将第一、第二捕获组交换位置,用尖括号标识出来FROM TMPWHERE ID = replace;

--综合示例WITH SUDOKU AS(SELECT 020000080568179234090000010030040050040205090070080040050000060289634175010000020 AS LINEFROM DUAL),TMP AS(SELECT REGEXP_SUBSTR(LINE, \d{9}, 1, LEVEL) ROW_LINE, LEVEL COLFROM SUDOKUCONNECT BY LEVEL <= 9)SELECT REGEXP_REPLACE(ROW_LINE, (\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d), \1 \2 \3 \4 \5 \6 \7 \8 \9) ROW_LINEFROM TMP

Oracle正则表达式函数:regexp_like、regexp_substr、regexp_instr、regexp_replace