一、问题背景
最近工作中遇到一个问题,需要从将Oracle某个表中的特定字段包含的URL链接给清除或者替换成新的URL。经过查阅Oracle相关文档发现其提供了对应的正则匹配函数,遂记录一下以便后续查阅。
演示:
drop table posix_tbl;
create table posix_tbl(
datastr varchar2(200)
);
--truncate table posix_tbl;
insert into posix_tbl values('{"URL":"http://www.baidu.com?ad=123","data":"baidu"}');
insert into posix_tbl values('{"URL":"https://www.bing.com/qry/xxx","data":"bing"}');
select regexp_replace(datastr,'"https?://[^"]+','"https://google.com',1,1,'i') result from posix_tbl;
update posix_tbl p set p.datastr = regexp_replace(datastr,'"https?://[^"]+','"https://google.com',1,1,'i');
结果:
二、Oracle常用正则匹配函数
函数名 | 说明 |
---|---|
REGEXP_LIKE | 类似于 LIKE 运算符,但执行正则表达式匹配而不是简单的模式匹配 |
REGEXP_INSTR | 在给定字符串中搜索某个正则表达式模式,并返回匹配项的位置。 |
REGEXP_REPLACE | 搜索某个正则表达式模式并使用替换字符串替换它 |
REGEXP_SUBSTR | 在给定字符串中搜索某个正则表达式模式并返回匹配的子字符串 |
1.REGEXP_LIKE
REGEXP_LIKE(source_char, pattern
[, match_param ]
)
source_char:源字符串
pattern: 正则表达式
match_param:
c-大小写敏感,i-大小写不敏感
演示:
2.REGEXP_REPLACE
REGEXP_REPLACE ( source_char, pattern
[, replace_string
[, position
[, occurrence
[, match_param ]
]
]
]
)
position:搜索起始位置,默认为1意义为从source_char的第1位开始用pattern匹配。 occurrence:一个非负整数,指示发生了替换操作: 如果指定 0,则 Oracle 将替换所有匹配项。 如果您指定一个正整数 n,那么 Oracle 将替换第 n 次出现。
3.REGEXP_INSTR & REGEXP_SUBSTR
REGEXP_SUBSTR ( source_char, pattern
[, position
[, occurrence
[, match_param
[, subexpr ]
]
]
]
)
REGEXP_SUBSTR ( source_char, pattern
[, position
[, occurrence
[, match_param
[, subexpr ]
]
]
]
)
subexpr: 第n个子表达式