基础:
'^' 匹配输入字符串的开始位置,在方括号表达式中使用,此时它表示不接受该字符集合;
'$' 匹配输入字符串的结尾位置;
'.' 匹配除换行符之外的任何单字符;
'?' 匹配前面的子表达式0次或1次。
'+' 匹配前面的子表达式1次或n次。
'*' 匹配前面的子表达式0次或n次。
'|' 指明两项之间的一个选择。例子'^([a-z]+|[0-9]+)$'表示所有小写字母或数字组合成的字符串;
'( )' 标记一个子表达式的开始和结束位置;
'[]' 标记一个中括号表达式;
'{m,n}' 一个精确地出现次数范围,m=<出现次数<=n,'{m}'表示出现m次,'{m,}'表示至少出现m次;
字符簇:
[[:alpha:]] 任何字母。
[[:digit:]] 任何数字。
[[:alnum:]] 任何字母和数字。
[[:space:]] 任何白字符。
[[:upper:]] 任何大写字母。
[[:lower:]] 任何小写字母。
[[:punct:]] 任何标点符号。
[[:xdigit:]] 任何16进制的数字,相当于[0-9a-fA-F]
例子:
--查询value中以1开头60结束的记录并且长度是7位
select * from fzq where regexp_like(value,'1....60');
--查询value中以1开头60结束的记录并且长度是7位并且全部是数字的记录;
select * from fzq where regexp_like(value,'1[0-9]{4}60');
select * from fzq where regexp_like(value,'1[[:digit:]]{4}60'); -- 也可以这样实现,使用字符集
-- 查询value中不是纯数字的记录
select * from fzq where not regexp_like(value,'^[[:digit:]]+$');
-- 查询value中不包含任何数字的记录。
select * from fzq where regexp_like(value,'^[^[:digit:]]+$');
--查询任何包含标点符号的记录。
select * from fzq where regexp_like(value,'[[:punct:]]');
语法:
Oracle 10g提供了四个regexp function: REGEXP_LIKE , REGEXP_REPLACE , REGEXP_INSTR , REGEXP_SUBSTR
REGEXP_LIKE:比较一个字符串是否与正则表达式匹配
(srcstr, pattern [, match_option])
REGEXP_INSTR:在字符串中查找正则表达式,并且返回匹配的位置
(srcstr, pattern [, position [, occurrence [, return_option [, match_option]]]])
REGEXP_SUBSTR:返回与正则表达式匹配的子字符串
(srcstr, pattern [, position [, occurrence [, match_option]]])
REGEXP_REPLACE:搜索并且替换匹配的正则表达式
(srcstr, pattern [, replacestr [, position [, occurrence [, match_option]]]])
explanation:
srcstr: 被查找的字符数据。
pattern: 正则表达式。
occurrence: 出现的次数。默认为1。
position: 开始位置
return_option: 默认值为0,返回该模式的起始位置;值为1则返回符合匹配条件的下一个字符的起始位置。
replacestr: 用来替换匹配模式的字符串。
match_option: 匹配方式选项。缺省为c。
c:case sensitive
I:case insensitive
n:(.)匹配任何字符(包括newline)
m:字符串存在换行的时候被作为多行处理
eg:
select regexp_replace('create or replace procedure p_test is
1 l_id int;
3 begin
4 set transaction read only;
5 select id into l_id from t1;
6 dbms_output.put_line(l_id);
7 dbms_lock.sleep(15);
8 select id into l_id from t1;
9 dbms_output.put_line(l_id);
10 end p_test',
'[[:digit:]]{1,2} {1}',
' ')
from dual; ---替换掉开头的数字
select *
from test /* for update */
where regexp_like(last_name, '^a{2}.{0,}b{1}$', 'i');
select *
from test /*for update*/
where lower(last_name) like '[0-9]%';
select *
from test /* for update */
where regexp_like(last_name, '^[[:digit:]].{0,}[[:alpha:]]$', 'i'); ---数字开头,字母结尾
select *
from test /* for update */
where regexp_like(last_name, '[[:alnum:]]{4,}', 'i'); --四位数字或者字母
select *
from test /*for update*/
where regexp_like(last_name, '[[:space:]]{1,}') --有1个以上空格的
select regexp_substr('dfadfff', '(d).*(f{3})', 3) from dual; -- 返回从第3位开始的匹配字符串
select regexp_instr('dfadfff', '(d).*(f{3})', 3) from dual; --返回从第3位开始匹配字符串的index