Oracle使用正则表达式4个主要函数:
1、regexp_like 只能用于条件表达式,和 like 类似,但是使用的正则表达式进行匹配,语法很简单:
2、regexp_substr 函数,和 substr 类似,用于拾取合符正则表达式描述的字符子串,语法如下:
3、regexp_instr 函数,和 instr 类似,用于标定符合正则表达式的字符子串的开始位置,语法如下:
4、regexp_replace 函数,和 replace 类似,用于替换符合正则表达式的字符串,语法如下:
这里解析一下几个参数的含义:
1、source_char,输入的字符串,可以是列名或者字符串常量、变量。
2、pattern,正则表达式。
3、match_parameter,匹配选项。
取值范围: i:大小写不敏感; c:大小写敏感;n:点号 . 不匹配换行符号;m:多行模式;x:扩展模式,忽略正则表达式中的空白字符。
4、position,标识从第几个字符开始正则表达式匹配。
5、occurrence,标识第几个匹配组。
6、replace_string,替换的字符串。
--创建表及测试数据
create table tmp as
with data as (
select 'like' as id ,'a9999' as str from dual union all
select 'like' ,'a9c' from dual union all
select 'like' ,'A7007' from dual union all
select 'like' ,'123a34cc' from dual union all
select 'substr' ,'123,234,345' from dual union all
select 'substr' ,'12,34.56:78' from dual union all
select 'substr' ,'123456789' from dual union all
select 'instr' ,'192.168.0.1' from dual union all
select 'replace' ,'(020)12345678' from dual union all
select 'replace' ,'001517729C28' from dual
)
select * from data ;
SELECT * FROM tmp;
--查询结果如下
--regexp_like 示例
--1.匹配有字母 "a"的字符不区分大小写,且匹配任意数字
\d :匹配任意数字字符
select str from tmp where id = 'like' and regexp_like(str,'a\d+','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示例1
SELECTstr,
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示例2
SELECTSTR,
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示例1
SELECTSTR,
REGEXP_INSTR(STR, '\.') IND,
REGEXP_INSTR(STR, '\.', 1, 2) IND,
REGEXP_INSTR(STR, '\.', 5, 2) INDFROM TMPWHERE ID = 'instr';
--regexp_instr示例2
SELECTregexp_instr('192.168.0.1','\.',1,level) ind , -- 点号. 所在的位置regexp_instr('192.168.0.1','\d',1,level) ind -- 每个数字的位置from dual
connect 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 SUDOKU
CONNECT 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
源文:https://www.cnblogs.com/suinlove/p/3981454.html