sql - Oracle Regex Replace With Condition
问题描述
I'm new to use RegEx and I am trying to apply REGEXP_REPLACE with conditions if special character exists then apply regex else apply other regex for example
SELECT REGEXP_REPLACE ('PCB terminal block - FRONT 2,5-V/SA 5/10 BK - 1109601', '([^\-]+$)' , '') FROM dual;
output
PCB terminal block - FRONT 2,5-V/SA 5/10 BK -
above regex remove after last (-) and it's OK
but if my string does not contains (-) then this will return null as below
SELECT REGEXP_REPLACE ('PCB terminal block, nominal current: 4 A, rated voltage (III/2): 250 V, nominal cross section', '([^\-]+$)' , '') froM dual
output
null
i want to change this regex to return the string if it's not contains (-) is it possible?
解决方案
The problem is that you original expression is too broad. It matches on a sequence of characters other than the dash (-
) at the end of string: so if the string contains no dash, it matches entirely, and is suppressed.
You can add the dash to the regular expression, so it is part of the match. Unmatched strings are left untouched by REGEXP_REPLACE()
:
SELECT REGEXP_REPLACE (mycol, '-[^-]+$' , '-') FROM dual;
with t as (
select 'PCB terminal block, nominal current: 4 A, rated voltage (III/2): 250 V, nominal cross section' mycol from dual
union all select 'PCB terminal block - FRONT 2,5-V/SA 5/10 BK - 1109601' from dual
)
select mycol, regexp_replace(mycol, '-[^-]+$' , '-') from t
MYCOL | REGEXP_REPLACE(MYCOL,'-[^-]+$','-') :-------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------- PCB terminal block, nominal current: 4 A, rated voltage (III/2): 250 V, nominal cross section | PCB terminal block, nominal current: 4 A, rated voltage (III/2): 250 V, nominal cross section PCB terminal block - FRONT 2,5-V/SA 5/10 BK - 1109601 | PCB terminal block - FRONT 2,5-V/SA 5/10 BK -
Note that it is not required, nor wanted, to escape the dash in the character class.
推荐阅读
- python - 如何在循环中的同一图表上绘制点而不是单独的图表?
- excel - 如何通过循环使用 VBA 在多个单元格(行和列)上实现 SumIfs?
- javascript - 有没有办法发送一个静态图像,它是一个在正文中的 png 用于 axios 帖子的反应?
- php - 如何作曲家安装最新的require-dev和最低的require
- html - CSS 样式以正确对齐 img 我希望它们在我的页面上的方式?
- ios - 如何使用 Alamofire.request() 将 XML 肥皂响应保存到文件?
- php - 我可以在表单中允许一个空的日期字段吗?
- http - Flutter:编辑配置文件返回 401 'Unauthenticated' 但在 POSTMAN 中工作
- hibernate - 用 new 和 Distinct 一起查询
- java - 带参数调用main方法时出错